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

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

Here is an old thread about it. http://laravel.io/forum/03-04-2014-hasmanythrough-with-many-to-many

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);
0

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

0

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

0

make sure all your foreign keys are indexed

0

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']);
    }
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mattusik mattusik Joined 12 Mar 2015

Moderators

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

Your logo here?

Laravel.io

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

© 2024 Laravel.io - All rights reserved.