Lazy & Eager Loading

The following text is taken from this article. I don’t know which ones lazy loading and which are eager loading:

Both examples are lazy loading.

Hi, but in the second example it said that eager!

My understanding is:

Given


public function relations()

{

    return array(

        'comments' => array(self::HAS_MANY, 'Comment', 'post_id',

                        'together'=>false),

    );

}

Lazy loading:


Controller

   $model = Post::model()->findAll();


View:

   echo $model->comments->title;

Eager Loading:


Controller

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


View:

   echo $model->comments->title;

Eager loading generates the SQL to pull the related information in the initial findByXXX() call. Lazy loading makes another SQL call when you first reference the relation’s information.

Thank you, but I still don’t understand what is the benefit of CDbCriteria::together property :(

I had to use ‘together’=>true; to get the CDbCriteria to actually pull in a relation.

When we don’t use with() method, always lazy loading performed whether or not use together property. When we use with() method, if together set true, eager loading performed. if together set false, lazy loading performed. if together not set, considered to be true.

The wording might have confused you. It says, "We can also dynamically set this option when we perform the eager loading", the key being "when we perform the eager loading". This is eager loading:




$posts = Post::model()->with(

            array('comments')

        )->findAll();



Adding the together option and setting it to false in an eager loading setup like this separates the SQL statements, turning it into a lazy load approach. That’s what the article was trying to explain.

Thank you very much georaldc. I don’t know English well. :lol: