不起作用,您可以使用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
用於手機或循環的所有用戶的第一個用戶的數量。