This is a bit of an interesting question, but I'm hoping to get some advice around how best to structure the a few Eloquent models and their relationships.
Summary
I'm attempting to create a structure that most elegantly represents a group of Products, Components, and Parts, and allows me to calculate the cost of both a Product and a Component.
An
App\Partis purchased from a third-party, so they will inserted into the database with unit cost.An
App\Componentis made from Parts (ie: a ComponentbelongsToMany()Parts, and vice versa). The cost of the Component is the sum of the App\Part prices, but the part can also be sold directly to a customer.An
App\Productis made up from both Parts and Components, with the cost being the sum of theApp\PartandApp\Componentcosts; therefore, both the Part and the ComponentbelongsToMany()Products.
A Product and a Component share many of the same data fields, such as a method of procedure (instructions for building the product/component), a sale price, etc.
Think of a part as something like a bolt or a piece of lumber, which can be used to make a table leg (a Component) which could then be used to create any number of different types of tables (a Product). The part can be used directly by the Product or by Components which are used to make the Product.
What I've Considered
I've come up with two different approaches so far, but neither of which really seem very clean, so my hope is that someone might steer me in better direction:
Leverage a Polymorphic relationship on the
App\Part, allowing it to be related to both theApp\Componentand theApp\Product, then a Many-to-Many relationship between theApp\Productand theApp\Component. The component will have to keep a record of it's calculated unit cost, then when calculating the cost of the Product, I can total the costs of both Parts and Components, and add them.When creating an
App\Component, add a reference to it back into thepartstable as a Part, ie: a table leg is made from a two different pieces of lumber, and some screws (I dunno, I'm not a carpenter). And then once an entry for table leg is created in thepartstable, theApp\Productjust needs a Many-to-Many relationship with the Parts.
The Ask
Neither one of these approaches sits with me particularly well, so I'd appreciate any advice from anyone with any suggestions, or anyone who might've tackled a similar problem in the past.
