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)