如何计算CakePHP中当前问题的分组记录(groupby / group)?

时间:2019-06-18 13:12:32

标签: count cakephp-3.0 query-builder cakephp-3.x paginate

通过在cakePHP中使用group,我们可以获得唯一的记录,但是我需要知道有多少记录重复? 我已经尝试过-> formatResults,-> virtualFields

'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;

还有其他方法可以减少代码,例如使用虚拟字段或其他方法吗?

2 个答案:

答案 0 :(得分:0)

您尝试过

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

$this->paginate($query);

答案 1 :(得分:-1)

您可以尝试以下方法:

在Paginator的控制器中,您可以这样使用:

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