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
可能的複製的[Laravel的MySQL ORDERBY計數(http://stackoverflow.com/questions/26375845/laravel-mysql-orderby-計數) –