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?

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