2017-09-13 58 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