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);
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.
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!
The Laravel portal for problem solving, knowledge sharing and community building.
The community