CakePHP3:如何获取关联的计数

CakePHP3: how to get the count of associated

我不明白如何指定一个查询来获取关联的计数。
在我的示例中,Agthemes 属于 Agplans。
在数据库中,4 个 Agthemes 属于 Agplan id 22,1 个 Agthemes 属于 Agplan id 23.

我目前编写了以下查询,其中 returns 第一个 Agplans 数组的 Agthemes 数组计数为 5,第二个为空 Agthemes 数组。

$agplans = $this->Agplans->find()
   ->contain([
           'Agthemes' => function ($q) {
               return $q->select(
                   [
                       'id',
                       'agplan_id',
                       'count' => $q->func()->count('*')
                   ]);
           }
       ])
   ->where([
            'site_id' => $site->id
      ])
   ->all();

如何正确编写这个查询?

您还必须对 Agthemes 进行分组

->contain([
    'Agthemes' => function ($q) {
        return $q->select(
            [
                'id',
                'agplan_id',
                'count' => $q->func()->count('*')
           ])
           ->group(['agplan_id']);
       }
   ])

hasMany实例的另一种方式。注意 leftJoin 而不是 contains。

$userTableQuery = $UsersTable->find();
$data = $userTableQuery
    ->select([
        'Users.id',
        'order count' => $userTableQuery->func()->count('Orders.id')
    ])
    ->leftJoinWith('Orders')
    ->group('Users.id');