samedi 31 août 2019

Laravel Accessor or HasManyThrough or something else?

I have four models: User, Product, Order, OrderItem

When a User adds an item to his cart, it creates a new Order and the item becomes a new OrderItem.

The tables:

users
    id - integer
    name - string

products
    id - integer
    name - string

orders
    id - integer
    user_id - integer
    paid - boolean

order_items
    order_id - integer
    product_id - integer
    quantity -integer
    price - double

Relationships:

`Product` hasMany `OrderItem`
`OrderItem` belongsTo `Order`
`OrderItem` belongsTo `Product`
`Order` hasMany `OrderItem`
`User` hasMany `Order`

I want to be able to list all Product and under each, all the Users who bought that Product (Order whereNotNull 'paid'). Inversely, I'd like to show a User all the Products they have purchased.

I've tried taking it in steps with relationships. I can get to work, but not

Laravel doesn't allow hasManyThrough relationships with a pivot table, which is essentially what order_items is, so that won't work.

Maybe I could do this with an Accessor with a join, but I can't wrap my head around it because I can't really set the relationship.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire