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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看