我有三个桌子,
User cities user_cities
id name title id name user_id city_id
1 aaa designer 1 cityA 2 1
2 bbb developer 2 cityB 2 3
3 ccc designer 3 cityC 1 2
4 ddd designer 3 3
5 rrr developer 3 2
4 2
4 3
现在,我将根据用户的title=designer
对其进行过滤。则过滤器数据将为
user
id name title
1 aaa designer
3 ccc designer
4 ddd designer
除了这些数据,我还必须获得像这样的城市的数量
data: {
0: {
name:cityB,
id:2,
count:3
},
1: {
name:cityC,
id:3,
count:2
}
}
我该如何用laravel雄辩地做到这一点?
答案 0 :(得分:0)
你可以
$users = App\User::where('title', 'designer')->get();
并使用
foreach($users as $user) {
$user->cities->count(); // collection count
}
但是更好的方法是Counting related models
$users = App\User::withCount('cities')->where('title', 'designer')->get();
然后
foreach($users as $user) {
$user->cities_count; // relationship count
}