我可以在不覆盖默认分页的情况下对自定义查询进行分页吗?

2021-12-21 00:00:00 mysql cakephp pagination having

在我的 CakePHP (1.2) 应用程序中,我有两个操作都使用分页 - 索引和搜索.

In my CakePHP (1.2) app, I have two actions that both use pagination - index and search.

在上一个问题中,我了解到,为了将阈值分数应用于搜索结果,我需要使用 HAVING MySQL 关键字.由于 CakePHP 本身不支持此功能,因此我需要下拉到自定义查询才能完成此操作.

In a previous question I learnt that, in order to apply a threshold score to search results, I need to use the HAVING MySQL keyword. Since CakePHP does not support this natively, I need to drop down to a custom query in order to accomplish this.

我能找到的关于自定义查询分页的所有指南都涉及覆盖 paginate()paginateCount() 方法.

All the guides I can find to custom query pagination involve overriding the paginate() and paginateCount() methods.

因为我仍然希望能够在索引上正常分页,所以我不想改变模型中的正常分页行为.

Since I still want to be able to paginate normally on the index however, I don't want to change the normal pagination behaviour in the model.

有什么办法可以(咳咳)我的蛋糕也吃吗?

Is there any way I can (ahem) have my Cake and eat it too?

推荐答案

实际上,如果你能用 find 你能用 paginate 做到.你可以看看这里

Actually if you CAN do it with find you CAN do it with paginate. You can take a look here

但是为了更具体,您可以将在 find 中使用的条件/限制/字段/包含/顺序等添加到分页功能中.

But to be more especific you can add the conditions/limit/fields/contain/order etc that you use in find to the paginate function.

我没有在分页中使用组,但它应该可以工作 :D

I haven't use group in the paginate but it SHOULD work :D

在你的情况下,你会有这样的事情:

In your case you will have something like this:

$this->paginate = array(
   'fields' => array(
        'Product.category_id',
        'COUNT(Product.hotel_id) as total'
    ),
   'group' => array(
        'Product.category_id HAVING COUNT(Product.hotel_id) > 1')
    )
);

$data = $this->paginate('Product');

希望它有效,对你的结果发表评论,如果它不起作用,你将不得不覆盖它,因为它不接受组条件......尽管我认为它会起作用,因为分页是在结束.

Hope it works, post a comment of your result, if it doesn't work you will have to override it, because it is not accepting the group condition... though I think it will work since pagination is a find in the end.

你可以尝试做这样的事情:

You may try to do something like this:

覆盖 paginate() 和 paginateCount() 但通过调整,潜入一个条件,这样你就可以判断它是否是一个分页.像这样:

Override the paginate() and paginateCount() but with a tweak, sneak a condition so you can tell if its a pagination with having or not. Something like this:

function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()){
   //if no having conditions set return the parent paginate 
   if (empty($conditions['having'])
       return parent::paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra)
   //if having conditions set return your override

//override code here

}

然后你在 paginateCount() 中做一些类似的事情,这样你就有了一个选择性分页.记住在不需要时取消设置 $conditions['have'] 或记住将它放在不影响您查找的地方;)

Then you do something similar in paginateCount(), that way you have a selective paginate. remember to do unset $conditions['having'] once it is not needed or remember to put it somewhere that doesn't affect your find ;)

相关文章