2015-09-11 64 views
0

該查詢是如下翻譯SQL查詢的CakePHP 3.0

select T.username, 
sum(T.size) as totSize, 
count(*) total, 
count(case when T.type = 'facebook' then 1 else null end) as facebook, 
count(case when T.type = 'instagram' then 1 else null end) as instagram, 
count(case when T.type = 'device' then 1 else null end) as device 
from (SELECT users.username, pictures.size, pictures.type from users left join pictures on pictures.user_id = users.id) as T 
group by T.username 

關聯到每個「用戶」有幾個「畫面」。 基本上,我想要做的是:

  1. 左按類型用戶加入和圖片表
  2. 計數圖片
  3. 總結畫面由用戶尺寸

的SQL查詢適用於數據庫時工作正常,但我需要在我的CakePHP 3.0應用程序中表示這一點。 我設法使用模型關聯LEFT JOIN表。在UsersTable:

$this->hasMany('Pictures', [ 
'foreignKey' => 'user_id', 
'joinType' => 'LEFT' 
]); 

然後在我的查找方法:

$options['contain'] = ['Pictures' => function ($q) { 
return $q 
->select(['user_id', 'size', 'type']);}]; 
$options['fields'] = array('Users.username'); 
$query = $this->find('all', $options); 

如何繼續查詢?如果我嘗試訪問包含的數據(與'Pictures.type'一樣),我返回SQL錯誤,指出該列不在字段列表中。 我覺得這可能是錯誤的方法,但我想不出其他方法。

在此先感謝!

+0

爲什麼子選擇,是這樣的表現有關係嗎?如果沒有測試,我可以想象非子查詢的使用可能實際上會更快。 – ndm

回答

0

解決

$options['contain'] = array('Users'); 
$query = $this->Pictures->find('all', $options); 
$query->select(['Users.username', 'Users.plan', 'Users.id']); 
$query->select(['sum' => $query->func()->sum('size'),]) 
     ->select(['count' => $query->func()->count('*'),]) 
     ->select(['facebook' => $query->func() 
      ->count('case when type = \'facebook\' then 1 else null end'),]) 
     ->select(['instagram' => $query->func() 
      ->count('case when type = \'instagram\' then 1 else null end'),]) 
     ->select(['device' => $query->func() 
      ->count('case when type = \'device\' then 1 else null end'),]) 
     ->group('user_id'); 

return $query; 

這允許選擇加盟領域

$result = $query->all(); 
$result->user->username;