sunedall
4 months ago

Querying model based by two different pivot tables

Posted 4 months ago by sunedall

Hi folks.

Been scratching my head with this one, since I'm not hardly skilled in Laravel and Eloquent yet. I've been searching in here (https://laracasts.com/discuss?q=multiple+pivots ), without hitting the right topic - or at least not getting any of the solutions to work.

App intro: I've got a small application, that is supposed to generate workout programs (querying exercises) for me based on selected equipment and selected bodyparts.

The problem: I'm working with three tables: exercises, bodypart_exercise and equipment_exercise. Last two is the pivot tables.

I want to find exercises where the bodypart_id could be X and the equipment_id could be Y - and the exercise_id in both cases are e.g. 4.

So my query would look something like this: Give me a collection of all exercises matching BOTH the bodypart_id and the equipment_id in the two pivot tables.

But I really can't figure it out. With one relationship I can do the following - but will only give me the exercises associated with the bodyparts.

$exercises = Exercise::whereHas('bodyparts', function ($query) use ($bodypartIds) {
    $query->whereIn('bodypart_id', $bodypartIds);
})->get();

Can someone help me out a bit? :-) Thanks in advance

Please sign in or create an account to participate in this conversation.