Specifying Limit In Each Has_Many Relations

Hi, I have 2 HAS_MANY relation in my blog controller; Images and Comments. When I do an eager loading, I would limit it to 5 image and 10 comments.

I have the following CDbCriteria code in my controller.


$criteria=new CDbCriteria;

$criteria->with=array(

 'images'=>array('limit'=>'5'),

 'comments'=>array('limit'=>'10'),

);

$criteria->condition="t.id = :id AND t.slug = :slug AND t.status = :status";

$criteria->params = array(

 ':id' => $id,

 ':slug' => $slug,

 ':status' => 1,

);

$model=Post::model()->find($criteria);

I have also tried specifying limit in the relation rules as follow but it doesn’t work as well.


return array(

 'images' => array(self::HAS_MANY, 'Image', 'post_id', 'limit'=>'5'),

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

);

It loads all images and comments. Am I missing something out here?

its not possible check this article out

http://www.yiiframework.com/forum/index.php/topic/20056-with-limit-not-lazy-load/

I realize this post is old, but the answers are sprinkled through a number of posts and it may benefit others to have a summary. Here’s a summary of what you need to limit eagerly loaded tables.

  • ‘together’ => true,

  • the limit should be part of the find method criteria and not within the relational ‘with’ array)


$model = User::model()->with( array( 

	'posts'=>array(

		'condition'=>'posts.type=1',

		//'joinType'=>'INNER JOIN',

		'together'=>true,

	)))->findByPk( $id, array('limit' => 4) );

You can also use the limit for other find methods besides findByPk. eg. (Find)