Just use has() instead of with(). Has() excepts your constraints too.
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.
It seems when using where('id', 3) it will select that one, but when you use another where('id', 5) it does not work (it probably uses the same record for that)
This is the code:
$keys = array_keys($request->genres);
$list = Movie::with('genres')->whereHas('genres', function ($query) use($keys) {
$query->where('id', 3)->where('id', 5); // testing it manually, but it must be done with the value in "$keys"
})->limit(3)->get();
It also has a pivot table, for relationship based on movie_id. If there is any other way, I'm hoping to hear that too. My preference is the best, clean and without much overhead.
Thank you in advance :)
Oke, I found something, it seems like this does the trick, but I think there must be a better way to do this.
$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());
It kinda feel like this will give a lot of overhead, is this the best way? Any other & better ways will be appreciated :) Solution mark will go to the best.
Please or to participate in this conversation.