cakephp 3.0 + 分组依据 + 计数 + 分页

cakephp 3.0 + group by + count +paginate

我有一个 table 用户和另一个 table 游戏。

现在用户将创建游戏。现在我想要用户列表以及他创建的游戏数量。

下面的查询将输出(IN PHPMYADMIN)正是我想要的。 但是我不知道如何在 cakephp 3.0 中触发这样的查询:

SELECT `users`.`id`,`firstname`,`lastname`,(select count(id) from games where games.created_by=users.id) FROm users group by `users`.`id`

在你的控制器中:

$users = $this->Users->find('all', [
        'fields' => [
            'id' => 'Users.id',
            'firstname' => 'firstname',
            'lastname' => 'lastname',
            'count_games' => 'COUNT(games.id)'
        ],
        'join' => [
            'table' => 'games', 
            'type' => 'LEFT',
            'conditions' => 'games.created_by = Users.id'
        ],
        'group' => ['Users.id'],
]);
$this->set('users', $users);
$this->set('_serialize', ['users']);

我正在使用下面的代码进行排序

<th><?= $this->Paginator->sort('count_games_created','Number of games created') ?></th>
<th><?= $this->Paginator->sort('count_games_joined','Number of games attended') ?></th>

经过大量研究,我提出了一个相当不错的解决方案:CounterCache !

每次您向 user 添加新的 game 时,用户 table 的游戏数 game_count 都会更新。 它有效,而且是 更快 的解决方案。