Mathéo
Mathéo

Reputation: 21

Retrieving relationships from relationships in Laravel

I have an application using Laravel 7. Within it, I have an "Account" model, this model has several "Profiles" and each "Profile" has several "Products".

How can I retrieve all the "Products" attached to certain "Accounts" in an optimal way.

Currently, I load all the "Profiles" linked to this "Account" and then all the "Products" linked to each "Profile". But I don't find this very optimized and have difficulties in sorting the returned data (in descending order).

I'm sure that Eloquent / Laravel allows to recover this directly, but I don't know how.

Thanks to you !

Upvotes: 2

Views: 70

Answers (2)

OMR
OMR

Reputation: 12188

eloquent has the relation 'Has Many Through' just for this kind of cases, in your Account Model you could write something like:

class Account extends Model
{
public function products()
{
return $this->hasManyThrough(Product::class, Profile::class);
}
}

now, you can get all product for specified account like:

$myAccountProducts=Account::find($account_id)->products()->get();

you can also specify foreign keys ...

more details in:

https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

Upvotes: 3

Omer YILMAZ
Omer YILMAZ

Reputation: 1263

Account::with(['profiles','profiles.products'])->get();

Upvotes: 4

Related Questions