Active Record Relations with Pagination

So I have the relation:

now I want to display this relation result with Pagination

etc, but How can I apply pagination on this? I want to be able to do it on the relation.

'posts' => array(self::HAS_MANY, 'Post', 'author_id'),

foreach ($model->posts as $post {

echo $post->title;

echo $post->details;


You will probably want to use CActiveDataProvider with CGridView or CListView.

$dataProvider = new CActiveDataProvider($model->posts, array(











$this->widget('zii.widgets.grid.CGridView', array(





$this->widget('zii.widgets.CListView', array(


    'itemView'=>'_post',   // refers to the partial view named '_post'



        'create_time'=>'Post Time',



This is not working with relations. It works on the model, but for some reason not the relation. if I replace $model->posts with $model or Posts it does it, but it doesn’t work for relations.


    $dataProvider= new CActiveDataProvider($model->posts);


    $this->widget('zii.widgets.grid.CGridView', array(




To tell you the truth if never tried to populate a DataProvider by a model relation. Why not create a Posts model?

The relation is doing the join with user id and the post.

so essentially $user->posts


The posts model already exists, but I don’t want to show all the posts. I want to show the posts for a specific user.

How about doing it the other way around and using a user relation and custom scope?


In your Posts model…


	* @return array relational rules.


	public function relations()


		return array(		








       //custom scope

       public function byUser($user_id)


		$with = array('user'=>array(


					  'joinType'=>'INNER JOIN',

					  'condition'=>' = '.$user_id,



		$this->getDbCriteria()->mergeWith(array('with' => $with ));

		return $this;


In your Controller…

 $criteria = new CDbCriteria();

 $criteria->together = true;

 $dataProvider = new CActiveDataProvider(Posts::model()->byUser([USER ID]), array(



$this->render('index', array('dataProvider' => $dataProvider));						

In your View…

$this->widget('zii.widgets.grid.CGridView', array(



Yep got it

I just did it the old fashion way :)

Thanks by the way :)

Please post your solution.