Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

munteanuserban's avatar

Fetch all products from more orders

Hi guys,

I have 3 tables : Order, Product and User. I want to display all orders made by a user with all products. ( ex : Order details + list all products, Order details + list all products )

I can't find the relationships beetween this 3 models. I know that :

  • order hasMany products
  • order belongsTo user
  • product belongsToMany order

If someone can explain/or show me how to make migrations and relationship beetween ? Thanks in advance.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You also will need a many-to-many relationship between Order and Product assuming a Product can be ordered more than once. This will require a pivot table order_product with product_id and order_id columns by convention. Then the Order model:

// Order

public function products()
{
    return $this->belongsToMany(Product::class);
}
// User
public function products()
{
    return $this->hasMany(Order::class);
}

Once the relationship has been properly established:

$user = User::with('orders.products')->get()
1 like

Please or to participate in this conversation.