2015-05-28 60 views
2

我有一个表格用户和另一个桌面游戏。cakephp 3.0 + group by + count + paginate

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

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

您需要阅读有关检索数据的文档 - http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html –

回答

4

在你的控制器:

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

亿万谢谢君.... – JPT

+0

HI this作品但分页排序链接不在两个领域工作。 – JPT

+0

“不工作”是什么意思? – Jun

0

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

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

后很多研究,我带着一个相当不错解决方案:CounterCache

每当您向user添加新的game时,用户表中的游戏数量game_count都会更新。 它的工作原理和它是一个更快解决方案。