Support the ongoing development of →
Database Eloquent
Last updated 2 years ago.

What you need is a "has many through many" relationship but laravel doesn't support it.

Here is an old thread about it.

There are some workarounds people have come up with and I can offer you another one which I think is pretty clean. It's a scope that has nested whereHas inside the model C

model C --

public function scopeHasAViaB($query, $ids) {
    if (empty($ids)) {
        return new \Illuminate\Database\Eloquent\Collection();
    return $query->whereHas('b', function ($query) use ($ids) {
            $query->whereHas('a', function ($query) use ($ids) {
                $query->whereIn('id', $ids);

-- controller code --

  $modelAkeys = [1,2]
    $cc = ModelC::HasAViaB($modelAKeys)->paginate(10);

Thank you, It works like a charm, but it takes a lot of time in case of ~5 mil C rows.


maybe you can modify your database structure. 3 tables with two pivot tables that's quite a complex structure.


make sure all your foreign keys are indexed


I created a HasManyThrough relationship with support for BelongsToMany: Repository on GitHub

After the installation, you can use it like this:

class A extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function c() {
        return $this->hasManyDeep(C::class, ['a_b', B::class, 'b_c']);

Sign in to participate in this thread!


Your banner here too?

mattusik mattusik Joined 12 Mar 2015


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.