Reputation: 65
I have an issue with a many-to-many polymorphic relationship (diagram below). In a food shop some products have options/variants, e.g. pizza comes in variants of 7inch, 12inch, 16inch. When pizza is added to cart a variant must be selected.
When an order is saved
- bought products (without variants) are saved in the orderables
table
- variants that are bought are saved in variant_orderables
table
Btw, the pivot tables are called orderables
and variant_orderables
instead of what you might expect according to Laravel conventions, e.g. "customer_order_product", because in addition to customer_orders
, the products
and variants
are also in a polymorphic relationship with stock_orders
(where the shop buys those items from suppliers). I just didn't show all that on the diagram to keep it simple.
Anyway, bought items, be they products
or variants
, can have "extras" added to them in the order. E.g. A pizza can have extra cheese, or pepperoni as extras (info contained in the extras_groups_offers
table).
ordered_extras
is where we will list the product
or variant
id of the extras that have been ordered, along with the orderables
or variant_orderables
id that the extras are applied on.
So between variants
and customer_orders
, variant_orderables
is the pivot, but then variant orderables
has a relationship with extras_groups_offers
with ordered_extras
as the pivot.
I know I probably need to do something with newPivot, but as this involves a few polymorphic many-to-many relationships, I'm not exactly sure how to go about it. If anyone could give me a simple example solution, I'd be very grateful.
Basically, I am trying to reach a stage where I can eager load all the necessary information for an order, including products/variants ordered, and all the ordered extras for each product/variant that has been ordered. I just don't know how to go about it.
Thanks.
Upvotes: 1
Views: 357
Reputation: 65
I've overcome the problem by making the orderables
and variant_orderables
tables as normal models. This means I do have more chaining to do in terms of relationships, but I can at least eager load multiple nested layers easily, e.g. order.orderProducts.extrasGroupsOffers
(P.S. orderables has been renamed to order_product, if you're wondering where that came from)
Upvotes: 1