排序 – Cakephp分页按计算字段排序(COUNT)

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了排序 – Cakephp分页按计算字段排序(COUNT)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在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"
                        );

(我不得不覆盖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']) &amp;& 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的好解决方案……你是怎么做到的?

提前致谢!

也许你的问题可以用 Virtual fields解决

如果为计算字段创建自定义字段,则可以使用该自定义字段上的Paginator-> sort()方法进行排序.

我在评论找到了解决方there(不需要使用自定义字段而不是adnan的初始解决方案来自定义分页方法等).

脚本宝典总结

以上是脚本宝典为你收集整理的排序 – Cakephp分页按计算字段排序(COUNT)全部内容,希望文章能够帮你解决排序 – Cakephp分页按计算字段排序(COUNT)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。