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(

			'pagination'=>array(

        			'pageSize'=>10,

   					 ),			

			'sort'=>array(

				'defaultOrder'=>array(

				  'title'=>false

				)

			  )

		 ));


//CgridView

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

    'dataProvider'=>$dataProvider,

));


//or


//CListView

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

    'dataProvider'=>$dataProvider,

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

    'sortableAttributes'=>array(

        'title',

        '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.


<?php

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

    


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

    'dataProvider'=>$dataProvider,

    ));


?>

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?

Example:

In your Posts model…





       /**

	* @return array relational rules.

	*/

	public function relations()

	{

		return array(		

		  'user'=>array(

				  self::BELONGS_TO, 

				  'Users', 

				  'author_id'

			  ),

		  

	}


       //custom scope

       public function byUser($user_id)

	{		

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

					  'select'=>false,

					  'joinType'=>'INNER JOIN',

					  'condition'=>'user.id = '.$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(

			'criteria'=>$criteria,

		 ));


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




In your View…




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

    'dataProvider'=>$dataProvider,

 ));



Yep got it

I just did it the old fashion way :)

Thanks by the way :)

Please post your solution.