Today we had a problem where a findAll() with criteria wasn’t bringing back expected results.
Yii appeared to be bringing back some results, but then as we looped through the CActiveRecord objects and attempted to access their relations, it became clear that because we didn’t have all the information we needed, Yii was almost ‘filling in the blanks’ and adding more records into our results – even records that weren’t possible given the original $CDbCriteria object passed into the findAll().
After a bit of head scratching and research, we worked out our query was missing one crucial element – the ‘together’ method. This guy makes sure that all the related tables requested in the ‘with’ method, or in the CDbCriteria are included and used properly:
$criteria = new CDbCriteria;
$criteria->condition = //.... etc
// Be sure to use ->with('joined_tables') ...
// and ->together() to make it all work!
$categories = Category::model()->with('products','products.images')->together()->findAll($criteria);
This gave us our correct array of CActiveRecord objects, with all the correct relations that we were then able to loop through, problem free.