在CakePHP 1.3中使用计算字段(例如COUNT())时,我在排序分页列表时遇到问题
原文链接:https://www.f2er.com/php/240076.html假设我有两个模型:文章和评论(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" );
(我不得不覆盖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>
它的工作原理……但似乎对于开发者应该透明的东西来说代码太多了. (感觉我正在做蛋糕的工作)所以我问是否还有另一种更简单的方法.也许蛋糕有这个功能,但决定隐藏它.. o_O ..在文档上没有关于这个,我还没有找到另一个关于S.O的好解决方案……你是怎么做到的?
提前致谢!