Eager Loading vs Lazy Loading

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

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


$comment = Comment::model()->findAll

2b. to get Issue:

$issue = $comment->issues

(assume that we have declared "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:

$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 efficency. Thank you!

Eager loading executes just one query:

$comments = Comment::model()->with('issues')->findAll();

// sql will get all comments with their issues all at once

foreach ($comments as $comment)


    $issues = $comment->issues;

    // $comment->issues is already populated

    // you can just access it, no sql needs to be executed at this point


Lazy loading executes 1 + N queries:

$comments = Comment::model()->findAll();

// sql will get all comments, but not with their issues

foreach ($comments as $comment)


    $issues = $comment->issues;

    // $comment->issues is not populated at this point

    // so, each comment object has to execute a sql to get related issues here


Thank you very much for your answer, Mr.Softark!

I basically get the idea of your explaination. Though the main point of my question you have explain very clearly, I still have one very small question need your help to fully understand your explaination.

When you wrote:

$issues = $comment->issues;

    // $comment->issues is not populated at this point

I pull my hair and trying to guess what does "populate" mean. Does it mean "massive assignment" to $issues AR instance attributes with the resources get from database query?

Thank you!

Yes, I mean that.