2015-05-28 61 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都會更新。 它的工作原理和它是一個更快解決方案。