2016-04-11 82 views
1

我想選擇所有類型爲的學生,並計算所有與他們連接的國家/地區的用戶數。順序應該基於與其相關的國家數量。Laravel查詢 - 按次數排序

用戶表:

id name 
1  user1 
2  user2 
3  user3 
4  user4 
5  user5 

國家表:

id  country_name 
1  America 
2  Australia 
3  Argentina 
4  Afghanistan 
5  India 

pivot_countries_user表:

id  user_id  country_id 
1  1   1 
2  1   2 
3  2   1 
4  3   1 
5  4   2 
6  5   2 
7  4   3 
8  1   4 

USER_TYPE表:

id type  user_id 
1  student 1 
2  student 2 
3  teacher 3 
4  lawyer  4 
5  teacher 5 

這裏的laravel查詢我想:

DB::table('users') 
->leftjoin('pivot_countries_user','pivot_countries_user.user_id','=','users.id') 
->leftjoin('countries','countries.id','=','pivot_countries_user.id') 
->leftjoin('user_type','user_type.user_id','=','users.id') 
->select('users.name','users.type', 
    DB::raw('count(pivot_countries_user.country_id)')) // should be per user but I don't know how 

預期輸出:

name  type  total_countries 
user1  student 3 
user2  student 1 
+0

可能的複製的[Laravel的MySQL ORDERBY計數(http://stackoverflow.com/questions/26375845/laravel-mysql-orderby-計數) –

回答

0

下面的查詢產生的預期輸出。

查詢生成器:

\DB::table('users as u') 
      ->leftJoin('pivot_countries_user as uc','uc.user_id','=','u.id') 
      ->leftJoin('user_type as ut','ut.user_id','=','u.id') 
      ->select([ 
       'u.name', 
       'ut.type', 
       \DB::raw('(SELECT count(*) FROM uc WHERE uc.user_id=u.id) as total_countries')]) 
      ->orderBy('total_countries','DESC'); 
2
DB::table('users') 
->leftJoin('pivot_countries_user','pivot_countries_user.user_id','=','users.id') 
->leftJoin('countries','countries.id','=','pivot_countries_user.country_id') 
->leftJoin('user_type', function ($join) { 
      $join->on('user_type.user_id', '=', 'users.id') 
       ->where('user_type.type', '=', 'student'); 
     }) 
->select('users.name','user_type.type', 
    DB::raw('count(countries.country_id) AS total_countries')) 
->groupBy('users.id') 
->get(); 

那麼你會得到預期的結果:
名     型                  total_countries
USER1      學生    USER2      學生