Search code examples
phppropel

Is Propel caching criteria when getting related objects?


I have a Propel 1.6 generated class Group that has Inits related to it, and Inits have Resps related to them. Pretty straightforward.

I don't understand the difference between these two pieces of Propel code. Here in the first one, I re-create the $notDeleted criteria on every loop. This code does what I want -- it gets all the Resps into the $data array.

foreach ($group->getInits() as $init) {
    $notDeleted = RespQuery::create()->filterByIsDeleted(false);
    foreach ($init->getResps($notDeleted) as $resp) {
        $data[] = $resp;
    }
}

Here in the second code, I had the $notDeleted criteria pulled out of the loop, for (what I thought were) obvious efficiency reasons. This code does not work the way I want -- it only gets the Resps from one of the Inits.

$notDeleted = RespQuery::create()->filterByIsDeleted(false);
foreach ($group->getInits() as $init) {
    foreach ($init->getResps($notDeleted) as $resp) {
        $data[] = $resp;
    }
}

I thought it must be something to do with how the getResps() method caches the results, but that's not how the docs or the code reads in that method. The docs and the code say that if the criteria passed in to getResps() is not null, it will always get the results from the database. Maybe some other Propel cache?


Solution

  • (First off, I'm guessing you meant to use $init versus $initiative in your loops. That or there's some other code we're not seeing here.)

    Here's my guess: In your second example you pull out the $notDeleted Criteria object, but each time through the inner foreach the call to getResps($notDeleted) is going to make Propel do a filterByInit() on the Criteria instance with the current Init instance. This will add a new WHERE condition to the SQL, but obviously a Resp can only have one Init.Id value, hence the lone result.

    I don't think there is a good reason to pull that out though, under the covers Propel is just creating a new Criteria object, cloning the one you pass in - thus no real memory saved.