0

I have 3 database tables (users, marketplaces, orders). One user can have many marketplaces and one marketplace has a morphMany relationship with orders. My user model: `

public function marketplaces(): BelongsToMany
{
    return $this->belongsToMany(Marketplace::class);
}

Marketplace model:

public function orders()
{
    return $this->morphMany(Order::class, 'orderable');
}

`

I need to retrive the orders which is ordered by a spacific user through his many marketplaces. How can I do that with the help or eloquent in laravel?

1 Answers1

0

In order to retrieve nested relationships with Eloquent, you have to use with function. For example:

$user = User::with('marketplaces')->first();

or

$user = User::with('marketplaces.orders')->first();

The second example brings every order that is related on each marketplace that is connected with the user. You can also use function to build your own query inside the with if you want to add some conditions on the query. For example:

$user = User::with(['marketplaces.orders' => function ($query) {
    $query->where('id', 1);
}]);
gkouem
  • 51
  • 3