欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel attach pivot to table with multiple values

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.

shareimprove this question
 
正确答案 

You can.

From this example in Docs (4.25.0):

$user->roles()->sync(array(1 => array('expires' => true)));

Hardcoded version for the first two rows:

$food = Food::find(1);
$food->allergies()->sync([1 => ['severity' => 3], 4 => ['severity' => 1]]);

Dynamically, with your arrays $allergy_ids and $severities in a compatible state (size and sort), you shall prepare your sync data before. Something like:

$sync_data = [];
for($i = 0; $i < count($allergy_ids); $i++))
    $sync_data[$allergy_ids[$i]] = ['severity' => $severities[$i]];

$food->allergies()->sync($sync_data);
shareimprove this answer
 
   
Great you solved my problem @Nuno Rafael Figueiredo this worked for me – sanu Oct 21 '15 at 17:30
   
@sanu. I'm glad, but shouldn't you upvote my answer? – Nuno Rafael Figueiredo Oct 22 '15 at 19:02
   
Right answer. Needs to be accepted. – frostymarvelous Jan 24 '16 at 10:40
1 
Works for 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 of detach() and then attach(). Note exactly equal, but close since exisitng records won't be detached first. – frostymarvelous Jan 24 '16 at 11:44
   
Accepting this as the answer due to more upvotes, and appears to be more relevant than the old answer from 2 years ago. – duncanogle May 22 '16 at 6:35

You can't do it like you' like so I suggest a simple loop:

foreach ($allergy_ids as $key => $id)
{
  $food->allergies()->attach($id, array_get($severity_ids, $key));
  // should you need a sensible default pass it as a 3rd parameter to the array_get()
}

workaround However if you wanted to attach multiple allergies with single severity level/id then you could do this:

$food->allergies()->attach($allergy_ids, array('severity' => $singleSeverityValue));
shareimprove this answer
 
   
foreach ($allergy_ids as $key => $id) { $food->allergies()->attach([$id], ['severity' => array_get($severity_ids, $key)]); } This is the updated version of the code that I used to get it to work. Turns out the attach method expects array to be passed to it. Thank you! – duncanogle Apr 22 '14 at 18:50
   
You mean it didn't work for you without casting $id to an array? It shouldn't be a problem as attach method casts it to array anyway. – Jarek Tkaczyk Apr 22 '14 at 18:54
   
@JarekTkaczyk That did the trick! =>, my problem was that I had a comma instead :-P – Pathros Jan 22 '16 at 22:08

来自  https://stackoverflow.com/questions/23226802/laravel-attach-pivot-to-table-with-multiple-values


普通分类: