Cakephp 使用having Clause 进行分页

问题描述 投票:0回答:1

是否可以将以下查询与 Cakephp 分页一起使用?

select u.email,(select count(*) from relatives as iu where iu.user_id=u.id ) as iu_count,(select count(*) from friends as ff where ff.user_id=u.id ) as ff_count from users as u having (iu_count>0 OR ff_count>0)

我尝试使用 cakephp 分页来执行此操作,但它给出了一个错误,因为“iu_count”和“ff_count”在查询的选择部分中不可用,但它们在having子句中可用。我的cakephp分页查询如下。

SELECT COUNT(*) AS `count` FROM `abc`.`users` AS `User` WHERE 1 GROUP BY `User`.`id` having (iu_count>0 OR ff_count>0) 

需要帮助/指导来处理此问题。

php cakephp pagination cakephp-2.0
1个回答
1
投票

今天我用谷歌搜索了更多,找到了一个适合我的解决方案。解决方案是重写 Model 中的 paginateCount 方法。

下面是一个被重写的函数。

public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
        $parameters = compact('conditions', 'recursive');

        if (isset($extra['group'])) {
            $parameters['fields'] = array("iu_count","ff_count");
            //$parameters['fields'] = $extra['group'];
            if (is_string($parameters['fields'])) {
                // pagination with single GROUP BY field
                if (substr($parameters['fields'], 0, 9) != 'DISTINCT ') {
                    $parameters['fields'] = 'DISTINCT ' . $parameters['fields'];
                }
                unset($extra['group']);
                $count = $this->find('count', array_merge($parameters, $extra));
            } else {
                // resort to inefficient method for multiple GROUP BY fields
                $count = $this->find('count', array_merge($parameters, $extra));
                $count = $this->getAffectedRows();
            }
        } else {
            // regular pagination
            $count = $this->find('count', array_merge($parameters, $extra));
        }
        return $count;
    }

这里“数组(“iu_count”,“ff_count”);”是我在 HAVING 子句中使用的虚拟字段。如果 HAVING 子句中没有需要的虚拟字段,则将 $extra['group'] 分配给 $parameter['fields'] 。

希望这个解决方案能够帮助一些人。

© www.soinside.com 2019 - 2024. All rights reserved.