AR + pagination issues

I have 3 tables: Categories(id, name, alias) <-> CategoryPost(category_id,post_id) <-> Posts(id, name, content) and have defined categories to have a MANY MANY relationship with Posts and vice versa with Categories.

I want to list Posts respective to their category alias. In my Posts controller I have this:


	

public function actionList()

	{

		$criteria=new CDbCriteria;


		$pages=new CPagination(Merchants::model()->count($criteria));

		$pages->pageSize=self::PAGE_SIZE;

		$pages->applyLimit($criteria);


		$models = Categories::model()->findByAttributes(array('alias'=>'laptops'))->posts;


		$this->render('list',array(

			'models'=>$models,

			'pages'=>$pages,

		));

	}



This does retrieve posts by category alias, but how do I implement this into the pagination? I’m lost for ideas ???

Thanks.

Use the True Power of Relations. ;)

Categories::model()->with(‘posts’)->findByAttributes(array(‘alias’=>‘laptops’));

This way you can count the result set with ease.

This seems to give a similar result to Categories::model()->findByAttributes(array(‘alias’=>‘laptops’))->posts

but when I try Categories::model()->with(‘posts’)->findByAttributes(array(‘alias’=>‘laptops’))->count(); it gives me the total number of categories.

Would there be a way to something like Categories::model()->with(‘posts’)->findByAttributes(array(‘alias’=>‘laptops’))->posts->count() ?

count( Categories::model()->with(‘posts’)->findByAttributes(array(‘alias’=>‘laptops’))->posts );

That seems to work, thanks!

Although I have just been looking at the blog demo and seems like its implementing a similiar idea to me except it is using tags and posts.

so in my Posts Model I put




// Posts Model

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'categories'=>array(self::MANY_MANY, 'Categories', 'categories_posts(post_id, category_id)'),

			'categoryFilter'=>array(self::MANY_MANY, 'Categories', 'categories_posts(posts_id, category_id)',

				'together'=>true,

				'joinType'=>'INNER JOIN',

				'condition'=>'??.alias=:alias'),

		);

	}



and in the controller




// Posts Controller

$withOption['categoryFilter']['params'][':alias']='laptop';

$postCount=Posts::model()->with($withOption)->count($criteria);	



I think the latter would be the better option? Since I can customize the criteria depending on the query? Unless theres a more efficient way?

You can customize your criteria in the former way as well, but copying demo sources is always a good decision to gather experience regarding Yii.

Good luck!