2016-07-15 66 views
0

我有一組用戶ID,我嘗試獲取其集合。我一直在使用下面的foreach循環,但是我意識到對於每個循環它都會覆蓋以前的數據。Laravel從ID數組獲取集合

$users = DB::table('user_tags')->where('tag_name', $tag)->whereNotNull('user_id')->lists('user_id'); 
$users = array_unique($users); 

foreach ($users as $key => $value) 
{ 
    $users = User::where('id', $value)->get(); 
} 

這怎麼能返回一個集合與所有用戶在該原始數組?

謝謝!

回答

7

有一個簡單的方法..

$ids = DB::table('user_tags')->where('tag_name', $tag)->whereNotNull('user_id')->lists('user_id'); 
$users = User::whereIn('id', $ids)->get(); 
+0

Q - 爲什麼'whereIn'與只是'where'? –

+1

where = id |在哪裏(ID數組) –

0

是多對多的使用者和標籤之間的關係?如果是這樣,請嘗試以下查詢:

User::whereHas('tags', function($query) use ($tag) { 
    $query->where('tag', $tag); 
})->pluck('id');