Using AR relations in CActiveDataProvider

Can’t find any cute sollution for the next problem:

Has some model: Post

It has relational models: Comment

How I can use it with pagination in CActiveDataProvider without calling find() (means with correct LIMIT options)?

This will load all comments from DB:




$post=Post::model()->findByPk(1);

$commentsDataProvider=new CActiveDataProvider(

	$post->comments,

	array('pagination'=>array('pageSize'=>10))

);



Most obvious way to solve it, is to create CDbCriteria for Comment model (with copy of relational rules from Post) and pass it into CActiveDataProvider.

Is there any other normal way to make it work correctly? (In case of complex relation to avoid duplication of code)

Not quite understood what you’re trying to acccomplish

This is how you create data provider for posts, gathering comments also




$dp=new CActiveDataProvider('Post', array(

        'criteria'=>array(

    	'with'=>array('comments')

  	),

  	'pagination'=>array(

		'pageSize'=>10

  	),

      )

);



‘comments’ should be a declared relation in your Post model in this case.

Hope it’ll help.

CActiveDataProvider docs

Hi Evgeny and yugene,

Assuming that "Post HAS_MANY Comments" and the "comments" relation is properly declared in Post model, we can say 3 things in creating CActiveDataProvider for "Post":

  1. There’s no need to specify “with” when you want lazy loading of comments.

  2. You should also specify "together" to "true" when you want eager loading of comments.

  3. You can not obtain the proper pagination when you set "together" to "true" … Try some searching in the forum for this problem.

@Evgeny:

For which model do you want CActiveDataProvider, "Post" or "Comment"?

And for which model do you want the pagesize, "Post" or "Comment"?

If both the answers are "Comments", then it should be quite easy …