不起作用,您可以使用user.id
(PK
)& phones.user_id
尝试这样的事情,假设关系是由:
$users = User::join('phones', 'users.id', '=', 'phones.user_id')
->groupBy('phones.user_id')
->select('users.*', 'phones.*', DB::raw('count(phones.user_id) countOfPhones'))
->get();
// Check the output
dd($users->toArray());
这会给你类似这样的东西(我在帖子中加入了文章mple):
array (size=4)
0 =>
array (size=14)
'id' => int 1
'first_name' => string 'Sheikh' (length=6)
// ...
'countOfPosts' => int 7 // <-- count of phones in your case
1 =>
array (size=14)
'id' => int 2
'first_name' => string 'Muhammed' (length=8)
'last_name' => string 'Usman' (length=5)
// ...
'countOfPosts' => int 2 <-- count of phones in your case
所以,使用$users->first()->countOfPhones
用于手机或循环的所有用户的第一个用户的数量。