3

I am playing with Yii and having some trouble with Yii Eager Loading vs lazy loading database query. For example comparing two ways:

  1. $comment = Comment::model()->with(array('issue'=>array('condition'=>'project_ id='.$projectId)))->findAll();

  2. 2a. $comment = Comment::model()->findAll

2b. to get Issue:

$issue = $comment->issues (assume that we have declare "issues" relation in Comment model).

I am not sure what advantages of the first approach. As I understand the 1st code will return only Comment BUT also run the get Issue query (like 2b code). However, as I see (thouth not sure there is better way to take advantage of "Eager Loading") if I want to get Issues of Comment in 1st code, I also have to run this code:

3.

$comment ->issues

If so, as I guest, we have to run 2 queries with the Eager loading approach, so it takes long time than "Lazy loading", because it run the "get Issue query" two times (fist time when we run the 1st code, and second time we run the 3rd code).

So, could you verify my though, or if it wrong could you tell me how to get all Issues from the Eager Loading approach that take advantage of its efficiency.

1 Answer 1

3

The matter about eager/lazy loading is not about how many lines of code you need, but how many resources it takes. When using eager loading, as in your first example, all of the elements of the 'issue' table which are associated to any comment will be loaded. They will be retrieved and preserved in memory, ready to be used. When you actually use them ($comment ->issues), they will be loaded from the memory cache, not from the database. Only one initial "big" query is performed. But if you have too many records associated and you won't use most of them, then lazy loading is the best option, as no record will be loaded from the database as long as you don't reference it. So when you reference a record, a query is performed. And that's how the story goes. So... eager loading or lazy loading, that's the question. :P `

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent explaination, very clear and easy to "digest". Thank so much Garcia!. Just one more small question: If I am in localhost, was the cache you mentioned above stored in a file? If it was then where I can find it? (I am using xampp 1.7.4). Thank you!
No, the results are just retrieved and cached in memory until the end of the execution of your script. You can look at your logs and get the SQL query if you want to see what is retrieved (and how it is retrieved)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.