Hello,
I have a question regarding the lazy loading AR approach.
I noticed that if I access a relation for the first time without defining any additional relation conditions etc during that access that the relation is saved in the model. This appears to prevent the AR model from performing the query again on subsequent accesses since the relation has already been loaded into the model’s memory.
//Example:
$myModel = User::model()->findByPk(1); // executes query
$x = $myModel->myRelation; // executes query
$y = $myModel->myRelation; // does NOT execute query
This is the behavior I expected.
However, I noticed that if I access a relation for the first time where I DO specify additional relation conditions during that access, the relation is NOT saved in the model. This, of course, results in the AR model executing the query again on subsequent relation accesses.
//Example:
$myModel = User::model()->findByPk(1); // executes query
$x = $myModel->myRelation(array('condition'=>'row_id='.$_GET['ID'])); // executes query
$y = $myModel->myRelation; // executes query
I was expecting the second access of myRelation in the example above to return the results from the conditional relation access just before it without executing a query…
I ultimately need to pass a condition into my relation as shown in the second example because the condition is based on user input, and I want the retrieved relation set to be saved in the model so subsequent accesses of that relation do not result in repeating the query resulting in a decrease in efficiency.
The "work around" here appears to be that if I need to lazy load with a condition, I need to assign the retrieved lazy loaded relation models to the model relation like so:
$myModel->myRelation = $myModel->myRelation(array('condition'=>'row_id='.$_GET['ID'])); // executes query
Then on subsequent accesses of myRelation, the query will not be repeated since the model relation is already populated:
$y = $myModel->myRelation; // does NOT execute query
This behavior seems odd to me. Is the intended behavior really that the relation should not be saved in the model if the relation is lazy loaded with additional conditions specified?
If so, is my “work around” the proper technique to accomplish my goal or did I miss something that isn’t as clumsy?
Thanks