2015-06-04 66 views
0

這裏是我的數據庫結構: DB structure如何在Laravel的特定用戶上選擇count()?

而且 - 有一個表用戶和reciever_id引用該表ID。 我使用該查詢來獲取每種通知類型的計數以及來自notification_types表的該類型通知的數據。

Notification:: 
      select('notification_types.*', DB::raw('count(*) as total')) 
      ->join('notification_types', 'notifications.type_id', '=', 'notification_types.id') 
      ->groupBy('notifications.type_id') 
      ->get() 

我需要的是對reciever_id設置約束,我只是沒有得到 - 我應該在哪裏放置where子句?

回答

2

剛剛鏈where方法get之前的任何地方,因爲你的病情會在notifications表適用於:

Notification::select('notification_types.*', DB::raw('count(*) as total')) 
    ->join('notification_types', 'notifications.type_id', '=', 'notification_types.id') 
    ->where('reciever_id', $receiverId) 
    ->groupBy('type_id') 
    ->get(); 

而且,沒有必要用此查詢組由notifications.type_idtype_id會做,因爲有在這裏創建沒有歧義,因爲沒有其他列名爲type_id

+0

該死的,我已經插入 - > where()before - > select(),爲什麼沒有它的工作,我必須把它放在groupBy之前? – naneri

+0

事實上,鏈接方法的順序並不重要,因爲Laravel查詢生成器確保它以正確的順序生成查詢字符串。所以你可能剛剛錯過了第一次:)。 – Bogdan