doushi1974 2015-03-04 17:42
浏览 39
已采纳

CakePHP - 使用DISTINCT时,分页总计数与实际计数不同

I have a find method that uses a DISTINCT clause to get results from my Model. The Controller code looks like below

$options = array(
    'limit' => 10,
    'fields' => array(
        'DISTINCT id', 'title', 
    ),
    'contain' => array(
        'Dealer' => array('id'),
    ),
    'paramType' => 'querystring'
);

$this->Paginator->settings = $options;
$cars = $this->Paginator->paginate('Car'); // returns 6 distinct rows

The above query return 6 distinct rows and 12 total rows. So when I am displaying, the screen shows 6 distinct rows

However in the View, when I use

echo $this->Paginator->param('count'); // returns 12

I get a count of 12

I checked the SQL Log and noticed that the count query is not using the distinct clause. Any idea how I can override the Paginator count query to use the DISTINCT clause?

  • 写回答

1条回答 默认 最新

  • dqrqp8492 2015-03-05 13:38
    关注

    Found the solution,

    1. In controller add distinct as an array parameter with other pagination options. So if I was trying to retrieve a list of Cars in my inventory with 10 cars at a time, the options would have a DISTINCT clause in the fields parameter and a separate parameter called distinct would also be added as shown below

      $options = array( 'conditions' => $conditions, 'joins' => $joins, 'limit' => 10, 'fields' => array( 'DISTINCT Car.id', 'title', 'user_id'), 'contain' => array( 'Dealer' => array('id'), ), 'paramType' => 'querystring', 'distinct' => 'Car.id' );

      $this->Paginator->settings = $options; $cars = $this->Paginator->paginate('Car');

    2. In Model, use the below function to override the original paginateCount method

      public function paginateCount($conditions = null, $recursive = 0, $extra = array()) { $parameters = compact('conditions', 'recursive'); if (isset($extra['distinct'])) { $parameters['fields'] = 'DISTINCT ' . $extra['distinct']; $count = $this->find('count', array_merge($parameters, $extra)); } else { // regular pagination $count = $this->find('count', array_merge($parameters, $extra)); } return $count; }

    3. No change in View

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化