【问题标题】:CakePHP - Pagination total count differs from actual count when using DISTINCTCakePHP - 使用 DISTINCT 时分页总数与实际计数不同
【发布时间】:2015-03-04 17:42:26
【问题描述】:

我有一个 find 方法,它使用 DISTINCT 子句从我的模型中获取结果。控制器代码如下所示

$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

上述查询返回 6 个不同的行,总共 12 行。所以当我显示时,屏幕显示 6 个不同的行

但是在视图中,当我使用时

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

我数到了 12

我检查了 SQL 日志并注意到计数查询没有使用 distinct 子句。知道如何覆盖 Paginator 计数查询以使用 DISTINCT 子句吗?

【问题讨论】:

    标签: php pagination cakephp-2.0


    【解决方案1】:

    找到解决办法,

    1. 在控制器中添加 distinct 作为具有其他分页选项的数组参数。因此,如果我试图一次检索我的库存中包含 10 辆汽车的汽车列表,则选项将在 fields 参数中有一个 DISTINCT 子句,并且还将添加一个名为 distinct 的单独参数,如下所示

      $options = 数组( '条件' => $条件, '加入' => $加入, '限制' => 10, '字段' => 数组( 'DISTINCT Car.id', 'title', 'user_id'), '包含' => 数组( '经销商' => 数组('id'), ), 'paramType' => '查询字符串', 'distinct' => 'Car.id' );

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

    2. 在模型中,使用下面的函数覆盖原来的paginateCount方法

      公共函数 paginateCount($conditions = null, $recursive = 0, $extra = array()) { $parameters = compact('条件', '递归'); if (isset($extra['distinct'])) { $parameters['fields'] = 'DISTINCT' 。 $extra['distinct']; $count = $this->find('count', array_merge($parameters, $extra)); } 别的 { // 常规分页 $count = $this->find('count', array_merge($parameters, $extra)); } 返回$计数; }

    3. 视图没有变化

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 2019-07-15
      相关资源
      最近更新 更多