Search within a model's HAS_MANY

If I have a model called Store which has a relationship like so:

'offers' => array(self::HAS_MANY, 'Offer', 'store_id'),

…and I want to search for all offers of that store which have, say a field called coupon == 0, is the best practice to iterate through Store’s $this->offers, or is there another way to do it?

If you don’t need any offers that don’t match any criteria other than ‘coupon == 0’ during that request then you should only ask the DB for those offers, like this:

//eager loading

$store = Store::model()->with('offers')->find(' = 0'); //or whatever other criteria

//lazy load

$store->offers(array('condition' => ' = 0'));

Thanks for your reply. I probably didn’t elaborate enough…sorry about that. Here’s another attempt:

Say I have an instance of a store and I already have all the offers loaded via ‘with’:

$mystore = Store::model()->with('offers')->findByPk(1);

…if I want to get all the offers for that store, I would do:


My question is, assuming the Offer model has a field called ‘coupon’, if I want all the offers for that store which have a coupon of 0, do I just do this:

$couponlessOffers = array();

foreach($mystore->offers as $offer) {

  if($ == 0) {

    $couponlessOffers[] = $offer;



…or is there a simpler way to get that set from the existing model instance without requerying?

[s]Once you have the model loaded and you saved it in a variable the db isn’t called again (except if you access a lazy load attribute). In your loop you are only accessing the values from the variable object. I would do it the same way.


I correct myself cause I now see the point of your answer ::)

I don’t know exactly if the offers are loaded each time in your loop when you have them already loaded before. You will see it if you enable sql logging…

I don’t think it requeries. I just wanted to know if iterating through the loop like that is the right way to do that, or if there’s some convenience call on the model that would get the subset of offers.