0

I have the following tables:

customers:
- id
- name

orders:
- id
- date
- customer_id

item_order:
- order_id
- item_id

items:
- id
- desc
- price

I know how to do the following:

  • 1:N relation between Customer and Order Eloquent models.
  • M:N relation between Order and Item Eloquent models.
  • 1:N relation between OrderItem and Order Eloquent models.
  • 1:N relation between OrderItem and Item Eloquent models.

But I want to create a M:N relation between Customer and Item. For example:

$customer = Customer::find(1)
$customer->items # returns a collection of all the items purchased by the customer

How can I do that with Eloquent?

Ricardo Pérez
  • 215
  • 1
  • 8
  • Maybe [Has Many Through](https://laravel.com/docs/8.x/eloquent-relationships#has-many-through) – ljubadr Jan 25 '22 at 08:57
  • 1
    And maybe [this SO question](https://stackoverflow.com/questions/34947862/how-to-use-hasmanythrough-with-more-than-3-tables-in-laravel) can help – ljubadr Jan 25 '22 at 08:59
  • 1
    Has Many Through doesn't work because it (IIRC) only works with one 1:N and then another 1:N relationships. – Ricardo Pérez Jan 25 '22 at 08:59
  • 1
    @ljubadr that will not work since there is a pivot table in the middle. there is no built in relation declaration that works that way. – N69S Jan 25 '22 at 08:59
  • 1
    https://stackoverflow.com/questions/37430217/has-many-through-many-to-many might help though it's for an older Laravel version – apokryfos Jan 25 '22 at 09:27

0 Answers0