Efficient AR use

I am constantly needing to retrieve values from a parent table when I use this one table. For example say I have a one-to-many relationship with an “Author” table to a “Book” table. Practically everytime I’m doing queries against the Book table I eventually need to get the Author.FullName field to display with my view. Currently, I’m using:




  $book->Author->FullName



Or similar syntax to get the values I wanted. From what I understand this forces a call to the database to retrieve the Author record. For a single Book this might not be a big deal, but for lists of books I’m afraid this may be too taxing. In some of my DTO objects I’ve used in the past I would make the AuthorFullname a Property in my Book object and always populate it using joins in my queries or using a database view. So, I’m wondering what would be the best way to approach this with ActiveRecord? Should I make “FullName” a property on my Book Object? If so, how would I tell AR to join this table when I do all my queries?

So, with the following code, how would I change this? As it is, this statement only get’s me the books, how do I include the Author table in one sweep?




public function getBooksByAuthorId($id) {

  $criteria=array(

    'condition'=>'Id='.$id,

    'order'=>'DateEntered DESC',

   );


  return $this->findAll($criteria);

}



Any alternatives or suggestions would be appreciated.

Thanks

You should use eager loading:




$books = Book::model()->with('Author')->findAll($crtieria);



http://www.yiiframework.com/doc/api/CActiveRecord#with-detail

andy_s

thanks for the reply. So, does this mean I still use the same syntax "Book->Author" and AR will already know that the Book has been retrieved for each record?

Yes. You may check out the guide under Performing Relational Query.

Yii, thanks for the link. Can’t believe I haven’t seen this page during my time going through the site.