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

devondahon's avatar

Getting entries from relationship and sub-relationship

I have three tables foo, bar and lorem. They are connected to each other with Many-To-Many relationships.

How can I efficiently get all entries of lorem where foo.id is 123, both directly and through bar (without duplicates) ?

Schema:

Foo -> Lorem          |
                      |----- MERGE
Foo -> Bar -> Lorem   |

I'm currently doing it this way:

# Get lorems from foos
$loremsA = Foo::find(123)->lorems()->get();

# Get ids of bars for given foo:
$bar_ids = Foo::find(123)->bars()->pluck('id')->toArray();
# Get lorems from bars
$loremsB = Lorem::whereHas('bars', fn($q) => $q->whereIn('id', $bar_ids))->get();

# Merge
$loremsB->merge($loremsA)

Is there any better way to do it ?

0 likes
1 reply
devondahon's avatar
Lorem::whereHas('bars', function($query) {
  $query->whereHas('foos', function($subQuery) {
    $subQuery->where('foos.id', 123);
  })
})->orWhereHas('foos', function($query){ 
  $query->where('foos.id', 123);
})->get();

Thanks to Tim Lewis

Please or to participate in this conversation.