CakePHP - Pagination total count differs from actual count when using DISTINCT

吃可爱长大的小学妹 提交于 2019-12-12 04:54:37

问题


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:


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



来源:https://stackoverflow.com/questions/28861232/cakephp-pagination-total-count-differs-from-actual-count-when-using-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!