Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lara75539's avatar

Querying model based by two different pivot tables

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

0 likes
3 replies
Digitalized's avatar
Level 10

Assuming you have an equipment relationship set up on your exercise model, try chaining an extra wherehas call onto your statement eg.

$exercises = Exercise::whereHas('bodyparts', function ($q1) use ($bodypartIds) {
    $q1->whereIn('id', $bodypartIds);
})->whereHas('equipment', function($q2) use ($equipmentIds) {
    $q2->whereIn('id', $equipmentIds);
})->get();

Hopefully that will give you what you want

lara75539's avatar

Thank you @digitalized! Exactly what I need.

Too damn stupid not thinking about chaining... Sometimes we all overthink ;-)

Please or to participate in this conversation.