I have a user page which shows his posts using pagination. I was wondering what the best way to do this is? This is what I have come up with, but it's not as elegant as it could be
<?php public function actionShow() { $user = $this->loadUser(isset($_GET['id']) ? $_GET['id'] : Yii::app()->user->id); $criteria=new CDbCriteria; $criteria->condition = '`post`.`user_id`=''.$user->id.'''; $pages=new CPagination(Post::model()->count($criteria)); $pages->pageSize=4; $pages->applyLimit($criteria); $user->post = Post::model()->with('parsecache')->findAll($criteria); $this->render('show', compact('user', 'pages')); }
Would it be possible to get it all the needed results with one query (and a JOIN)?
This is creating a redundant query also (the last one):
SELECT * FROM `user` WHERE `user`.`id`=1 LIMIT 1 SELECT COUNT(*) FROM `post` WHERE `post`.`user_id`='1' SELECT `post`.`id` AS t0_c0, `post`.`user_id` AS t0_c1, `post`.`title` AS t0_c2, `post`.`content` AS t0_c3, `post`.`created` AS t0_c4, `post`.`modified` AS t0_c5 FROM `post` WHERE `post`.`user_id`='1' LIMIT 4 SELECT `post`.`id` AS t0_c0, t1.`table` AS t1_c0, t1.`id` AS t1_c1, t1.`column` AS t1_c2, t1.`content` AS t1_c3 FROM `post` LEFT OUTER JOIN `parsecache` t1 ON t1.`id`=`post`.`id` AND `table`='post' WHERE `post`.`id` IN (5, 6, 63, 71)
And it should not need IN (5, 6, 63, 71)
since it already has the ON condition t1.id
=post
.id