2017-09-13 60 views
0

我有水果的數據庫條目,可以說,我想這一切的紅色水果:Laravel - 合併兩個表,然後取出根據這裏查詢

$allfruit = DB::table('fruits')->Where("color","=","red")->paginate(10); 

我也有用戶的表最不喜歡的水果。如果用戶在我試圖通過通過他們的ID來獲得他們所有的討厭水果的清單記錄:

$leastfav = DB::table('dislikes')->Where("userID","=",Auth::user()->id)->get(); 

現在我想要做的是從$allfruit刪除所有條目出現在與該用戶的ID「不喜歡」表。

我已經試過是一樣的東西:

$allfruit = DB::table('fruits')->Where("color","=","red")->merge($leastfav)->where(fruits.ID,"!=", "dislikes.fruitID")->paginate(10); 

我的DB是SQLite的,如果沒有什麼幫助。由於

+0

您使用的是什麼版本的Laravel? –

回答

1

你可以使用whereNotExists(的whereExists()倒數):

$allfruitQuery = DB::table('fruits')->where('color', 'red'); 

if (auth()->check()) { 
    $allfruitQuery->whereNotExists(function ($query) { 
     $query->select(DB::raw(1)) 
      ->from('dislikes') 
      ->where('userID', auth()->id()) 
      ->whereRaw('fruits.ID = dislikes.fruitID'); 
    }); 
} 

$allfuit = $allfruitQuery->paginate(10); 

或者,(如果你使用5.2+),你可以使用when()

$allfuit = DB::table('fruits')->where('color', 'red') 
    ->when(auth()->check(), function ($query) { 
     $query->whereNotExists(function ($query) { 
      $query->select(DB::raw(1)) 
       ->from('dislikes') 
       ->where('userID', auth()->id()) 
       ->whereRaw('fruits.ID = dislikes.fruitID'); 
     }); 
    }) 
    ->paginate(10); 

希望這有助於!

+0

完美!像魅力一樣工作,非常感謝:) – Hook