ple*_*ong 6 sorting pagination cakephp count aggregate-functions
在Cakephp 1.3中使用计算字段(例如COUNT())时,我在排序分页列表时遇到问题
假设我有两个模型:文章和评论(1篇文章x N条评论),我想显示文章的分页列表,包括每个文章的评论数量.我有这样的事情:
控制器:
$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"
);
Run Code Online (Sandbox Code Playgroud)
(我不得不覆盖该findCount()方法以便使用group by进行分页)
问题是在视图中,该sort()方法不起作用:
<th><?php echo $this->Paginator->sort('nbr_comments');?></th> //life is not that easy
Run Code Online (Sandbox Code Playgroud)
我能够通过"欺骗"分页和排序来创建一个解决方法:
调节器
$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;
}
Run Code Online (Sandbox Code Playgroud)
视图
<?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>
Run Code Online (Sandbox Code Playgroud)
它的工作原理......但似乎对于开发者应该透明的东西来说代码太多了.(感觉我正在做蛋糕的工作)所以我问是否还有另一种更简单的方法.也许蛋糕有这个功能,但决定隐藏它.. o_O ..在文档上没有关于这个,我还没有找到另一个很好的解决方案...你怎么做?
提前致谢!