1) Make a list of book IDs
foreach $product in Product-List $book_ids[$product->book_id] = $product->book_id;
Now request all book models (with index book_id )
$books = Book::model()->findAll(array( 'index' => 'book_id', 'condition' => 'book_id IN (' . implode(',', $book_ids). ')', ));
Integrate $books into your code, I believe that you are browsing all the products.
foreach $product in Product-List if( isset($books[$product->book_id]) ) $model = $books[$product->book_id]
2) Another way (I just assume that you have a product model)
in the product model add a relation to the book
public function relations() { ....... 'book'=>array(self::HAS_ONE, 'Book', 'book_id'), ....... }
When you receive the list of products, add the condition 'with' => array('book') with any of CActiveDataProvider or CActiveRecord ...
//Example $productList = Product::model()->findAll(array( 'with' => array('book'), )); foreach( $productList as $product ) { ....... if( $product->book != null ) $model = $product->book; ...... }
In any case, you can reduce SQL queries.
source share