Php Laravel查询-按计数排序
我想选择所有具有学生类型的用户,并统计与他们连接的所有国家/地区。顺序应以与之相关的国家数量为基础 用户表:Php Laravel查询-按计数排序,php,mysql,laravel,laravel-5,Php,Mysql,Laravel,Laravel 5,我想选择所有具有学生类型的用户,并统计与他们连接的所有国家/地区。顺序应以与之相关的国家数量为基础 用户表: 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 id user_id co
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
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
name type total_countries
user1 student 3
user2 student 1
国家/地区表:
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
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
name type total_countries
user1 student 3
user2 student 1
pivot\u countries\u用户表:
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
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
name type total_countries
user1 student 3
user2 student 1
用户类型表:
id type user_id
1 student 1
2 student 2
3 teacher 3
4 lawyer 4
5 teacher 5
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
以下是我尝试过的laravel查询:
id type user_id
1 student 1
2 student 2
3 teacher 3
4 lawyer 4
5 teacher 5
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
预期输出:
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
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
name type total_countries
user1 student 3
user2 student 1
下面的查询将生成预期的输出 查询生成器: 然后您将得到预期的结果:
nametypetotal_国家/地区
用户1学生3
user2student1
可能重复的