如何计算 cakePHP 中的分组(分组/分组)记录与我当前的问题



通过在 cakePHP 中使用 group,我们可以获得唯一的记录,但我需要知道有多少条记录是重复的?我尝试过 ->格式结果, ->虚拟字段,

'fields' => array('Table.column', 'count(*) as virtualColumn'),
'group' => array('Table.column HAVING COUNT(*) >= 1'),

但这也无济于事。我需要得到这个:

阵列 ( [A] => 10 [B] => 20 [C] => 30 (

以下是对我有用的代码:

$conditions = ['TableA.AnyColumn'=> $id];
$this->loadModel('TableA');
$this->TableA->belongsTo('TableB', [
    'className' => 'TableB',
    'propertyName' => 'table_b',
    'foreignKey' => false,
    'joinType' => 'LEFT',
    'conditions' => ['TableB.any_column = TableA.any_column', 'TableB.some_other_column = TableA.some_other_column']
]);

------- 在这里,我得到了计数-------

$count = $this->TableA->find()->where($conditions)->group(['columnToBeGroupBy']);
$count = $count->select(['columnToBeGroupBy', 'count' => $count->func()->count('TableA.columnToBeGroupBy')])->toArray();

------- 在这里,我得到了计数-------

$this->paginate = [
    'contain' => ['TableC' => ['fields'=>['fields required']]],
    'conditions' => $conditions,
    'group' => 'TableA.columnToBeGroupBy',
    'limit' => 20,
    'order' => ['TableC.modified' => 'DESC']
];
$result = $this->paginate($this->TableA);
$data['result'] = $result;
$data['pagination'] = $this->request->getParam('paging.TableA');
$data['count'] = $count;

有没有其他方法可以减少我的代码,比如使用虚拟字段或其他任何东西?

你试过吗

$this->loadModel('Articles');
$query = $this->Articles->find()->where($conditions)->group(['anyColumn']);
$query->select(['count' => $query->func()->count('Articles.anyColumn')])->toArray();
$this->paginate($query);

你可以试试这个:

在分页器的控制器中,您可以像这样使用:

  $itemads = $this->paginate($itemads, ['contain' => ['Departments', 'Stores'],'group'=>'upc','fields'=>array("upc_count"=>"COUNT(`upc`)")]);

最新更新