脚本宝典收集整理的这篇文章主要介绍了排序 – Cakephp分页按计算字段排序(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" );
(我不得不覆盖findCount()方法,以便使用group by进行分页)
<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的好解决方案……你是怎么做到的?
提前致谢!
以上是脚本宝典为你收集整理的排序 – Cakephp分页按计算字段排序(COUNT)全部内容,希望文章能够帮你解决排序 – Cakephp分页按计算字段排序(COUNT)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。