Question On Cactiverecord's With()

Hey guys,

          I've read Active Record section several times under The Definitive guide to Yii and can't fully understand the with() method of CActiveRecord class. In the guide, there is a something like this: 


                                      It explains as "the code will bring back posts together with their authors and categories".


                                       However, these is no categories like property in the Post class. What does "the code will bring back posts together with categories" mean?

                                       How can I access the categories stuff that brought back by the code above through $post?

                                       If I want to access the category id, I still have to do $posts->category->id, then why I need to do it with with() method?


Hi LeiLi, welcome to the forum!

It means that the related model instances are loaded at the same time.

Yes, you have to use that syntax to access the related model.

The difference lies mainly in efficiency of queries.

Lazy loading:

$post = Post::model()->findByPk($id);  // only loads $post

$authorName = $post->author->name;     // lazily loads $post->author

                                       // two queries at all

Eager loading:

$post = Post::model()->with('author')->findByPk($id);  // loads $post and $post->author

$authorName = $post->author->name;     // no query executed at this point

                                       // just 1 query at all

You make it so very clear by your examples. It is not so clearly explained in the documentation.

I have a question: when using with findAll, in terms of performance and rapidity of execution, does eager loading always produce faster results than lazy loading? Or does it also depend on the number of elements in the array returned?

You are right, Jimlam. Lazy loading is sometimes more efficient than eager loading.

Take a look at this section of the guide. :)

Hi Softark,

Thank you for the link pointing to some very interesting information. There is something I do not understand:

Is there any difference between :

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






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

Thanks a lot, softark! :lol: