【问题标题】:cakephp 3.0 + group by + count +paginatecakephp 3.0 + 分组 + 计数 + 分页
【发布时间】:2015-05-28 11:32:36
【问题描述】:

我有一个桌面用户和另一个桌面游戏。

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

下面的查询将输出(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`

【问题讨论】:

标签: mysql cakephp-3.0


【解决方案1】:

在您的控制器中:

$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']);

【讨论】:

  • 您好,这可以工作,但分页排序链接不适用于两个字段。
  • 如何与 $this->paginate 一起使用
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2017-01-13
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多