ackground
I'm creating a database revolving around food allergies and I have a many to many relationship between foods and allergies. There is also a pivot value called severity
which has a numerical number representing the severity of the allergy for that food item.
This link table looks like this;
food_id|allergy_id|severity
-------|----------|--------
1 | 1 | 3
1 | 4 | 1
2 | 2 | 1
The problem
When trying to update the link table with Eloquent (where $allergy_ids
is an array)
$food->allergies()->attach($allergy_ids);
How would I go about adding multiple values to this pivot table at once along with the pivot values?
I can add all the allergy_id
's for a particular food item in one go using the above line, but how can I also add in the severity
column at the same time with an array of various severity values? Maybe something like
$food->allergies()->attach($allergy_ids, $severity_ids);
Edit: There could be between 0-20 allergies for a specific food item, and a severity rating from 0-4 for each allergy, if this helps at all.
attach
as well. NOTE!!! Using sync will remove all not existing in$sync_data
and add those not existing in the table. It is the equivalent ofdetach()
and thenattach()
. Note exactly equal, but close since exisitng records won't be detached first. – frostymarvelous Jan 24 '16 at 11:44