Cakephp与有条款的分页

时间:2013-08-03 08:58:08

标签: cakephp pagination cakephp-2.0

是否可以在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) 

需要帮助/指导才能使用此功能。

1 个答案:

答案 0 :(得分: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;
    }

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

希望这个解决方案对某人有所帮助。