if your pivot starts to be more than a link between two tables then it should be its own model
Best practice with many-to-many relationships id's
Hi everyone,
I have some doubts with the many-to-many tables id's (primary key). A many-to-many relationship is composed, according to the Laravel documentation, of two models and three tables. Each model has its corresponding table, and the intermediate table has as fields:
- Auto-incremental ID
- table1_id
- table2_id
- other_attributes ...
So far, all good. I have already used it a lot, accessing the fields with the helper 'pivot', and updating these with 'updateExistingPivot' and more.
The question I have is whether it is worth taking advantage of the ID of the intermediate table such as FK from attributes of other tables.
EXAMPLE:
In my application, I have these models:
- Machine
- Product
- Restriction
And these four tables:
- machines (id, name, ...) [Machine]
- products (id, name, ...) [Product]
- machine_products (id, machine_id, product_id, price) [without model]
- restrictions (id, machine_product_id, day, begin_hour, end_hour) [Restriction]
Given a specific machine and a product, there are N restrictions. One restriction belongs to one specific Machine and Product.
As you can see, I took advantage of the autoincremental ID (primary key of the intermediate table), to relate the restrictions. But in this way, working with Eloquent is a bit weird, like accessing a Restriction from a Machine / Product or vice versa, is not easy:
Restriction::find( Machine::find(1)->products()->first()->pivot->id );
If I would get a Product or Machine from a given Restriction, I would have to find the 'machine_id' and 'product_id' from the row with the 'machine_product_id' of the Restriction that I had.
Could you tell me or recommend the best way to solve this dilemma? Already modifying the tables, models, or whatever it takes.
Thank you.
Please or to participate in this conversation.