Skip to content

Instantly share code, notes, and snippets.

@rakeshsoni18
Created July 11, 2019 17:40
Show Gist options
  • Select an option

  • Save rakeshsoni18/91925152dfe59576d076a67704057e4b to your computer and use it in GitHub Desktop.

Select an option

Save rakeshsoni18/91925152dfe59576d076a67704057e4b to your computer and use it in GitHub Desktop.
whereHas where multiple (must contain)
I'm in a bit of a situation with whereHas, the problem is I got a array with keys, I need to use those selected key to find results that contains all (ids that is contained within the array). The problem is it works with one, but when having more than one it does not work.
Solution:
Way-1
$keys = array_keys($request->genres);
$list = Movie::with('genres');
foreach($keys as $k => $v) {
$list->whereHas('genres', function ($query) use($v) {
$query->where('id', $v);
});
}
dd($list->limit(3)->get()->toArray());
Way-2
$keys = array_keys($request->genres);
$list = Movie::whereHas('genres', function ($query) use($keys) {
$query->whereIn('id', $keys); // use whereIn
})->limit(3)->get();
Way-3
$keys = array_keys($request->genres);
$list = Movie::whereHas('genres', function ($query) use($keys) {
foreach($keys as $key){
$query= $query>where('id', $key);
}
})->limit(3)->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment