2014-03-13 89 views
0

我有一種情況,我想從一個表(我的所有用戶)加載所有元素,並查看他們有多少可用手機。我知道可以加載所有手機,但這會導致太大的查詢。我怎樣才能加載手機的數量而不是他們的內容。Laravel關係:檢索一對多的數

我當前的代碼(工作,但檢索過大的結果)

$users= User::get(); 
$users->load('phones'); 

我不想做一個foreach,因爲我不希望有一個N+1 select issue

我不要計算在PHP中的數組,因爲它是不是最佳(檢索一切從DB只是做計數)

無的已經問的問題是令人滿意的:

回答

2

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