【发布时间】:2011-08-26 11:16:36
【问题描述】:
在 cakephp 1.3 中使用 COUNT() 等计算字段时,我对分页列表进行排序时遇到问题
假设我有两个模型:文章和评论(1 篇文章 x N cmets),我想显示文章的分页列表,包括每个文章的 cmets 数。我会有这样的东西:
控制器:
$this->paginate = array('limit'=>80,
'recursive'=>-1,
'fields'=>array("Article.*","COUNT(Comment.id) as nbr_comments"),
'joins'=>array(array( 'table' => 'comments',
'alias' => 'Comment',
'type' => 'LEFT',
'conditions' => array('Comment.article_id = Article.id'))
),
'group'=>"Article.id"
);
(我必须覆盖 findCount() 方法才能使用 group by 进行分页)
问题是在视图中,sort() 方法不起作用:
<th><?php echo $this->Paginator->sort('nbr_comments');?></th> //life is not that easy
我能够通过“欺骗”分页和排序来创建解决方法:
控制器
$order = "Article.title";
$direction = "asc";
if(isset($this->passedArgs['sort']) && $this->passedArgs['sort']=="nbr_comments")
$order = $this->passedArgs['sort'];
$direction = $this->passedArgs['direction'];
unset($this->passedArgs['sort']);
unset($this->passedArgs['direction']);
}
$this->paginate = array(... 'order'=>$order." ".$direction, ...);
$this->set('articles', $this->paginate());
if($order == "clicks"){
$this->passedArgs['sort'] = $order;
$this->passedArgs['direction'] = $direction;
}
查看
<?php $direction = (isset($this->passedArgs['direction']) && isset($this->passedArgs['sort']) && $this->passedArgs['sort'] == "nbr_comments" && $this->passedArgs['direction'] == "desc")?"asc":"desc";?>
<th><?php echo $this->Paginator->sort('Hits','clicks',array('direction'=>$direction));?></th>
而且它有效.. 但是对于一些应该对开发者透明的东西来说,似乎代码太多了。 (感觉就像我在做蛋糕的工作)所以我问是否有另一种更简单的方法。也许 cake 有这个功能,但决定隐藏它.. o_O.. 文档上没有关于这个的内容,我还没有在 S.O 上找到另一个好的解决方案......你是怎么做到的?
提前致谢!
【问题讨论】:
标签: sorting cakephp count pagination aggregate-functions