Minahgo's avatar

Many to Many Relationship with Extra Field

Hey there!

I may be blind or just too confused after a few hours of coding but I am stuck at a certain problem. Let me elaborate with some basic example.

I have 2 tables:

Recipe:

id
name
slug
description
collection_id

Ingredients

id
name

Ingredients can be in any recipe and every recipe can have very ingredient. To do this i went the common route of creating a pivot table and use Laravels many to many relations in the models.

recipes_ingredients

recipe_id
ingredient_id

That would make this possible:

Item = Potato

Recipe = Potato Soup
Added Item = Potato

Recipe = Mashed Potato
Added Item = Potato

So far so good. The hard part starts when every ingredient can be added in different amounts to different recipes. Lets just say we have:

Item = Potato

Recipe = Potato Soup
Added Item = 10x Potato

Recipe = Mashed Potato
Added Item = 5x Potato

How could something like that be achieved without too much tweaking? Is there any easy way? Thanks for the help!

0 likes
3 replies
leon@codecat.com.au's avatar
Level 2

You can register an extra 'quantity' field to your pivot table when defining the relationship by using withPivot(). Read here: http://laravel.com/docs/5.0/eloquent#working-with-pivot-tables

Alternatively, you could create a custom pivot model, however I think withPivot() will handle what you need.

Also as a side note, in your example, your pivot table name is not in the correct convention, it should be 'ingredient_recipe'. (Alphabetical order and singular). If you are overwriting this already for whatever reason, then that is fine.

3 likes
Minahgo's avatar

That was exactly what i was looking for! Thank you. The pivot table in the example was just randomly made up and I am way too tired to think straight but thank you for the info :).

erikbelusic's avatar

i was looking to do something similar. can you still use sync() or do you need to write a custom way to save these records?

edit - i think i already know that the answer is no.....the docs show sync only accepting ids. how would you go about updating the extra field? and what if you wanted to update many of the extra fields at once?

in context, im planning to do a pivot for user_id skill_id skill_proficiency. imagine assigning skills to a user and rating them on 1-5 scale

Please or to participate in this conversation.