Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel attach pivot to table with multiple values

Background

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.

like image 279
Duncan Ogle Avatar asked Apr 22 '14 17:04

Duncan Ogle


People also ask

What is attach () in laravel?

attach() inserts related models when working with many-to-many relations and no array parameter is expected. example: $user = User::find(1); $user->roles()->attach(1);

What is the use of pivot table in laravel?

The pivot table in laravel is a structured value that is grouped and aggregated in the individual items where the extensive table is obtained or accessed in the form of a spreadsheet, database, or other discrete functions.

How do I update a pivot table in laravel?

There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.


1 Answers

You can.

From this example in Docs (4.2, 5.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); 
like image 103
Nuno Rafael Figueiredo Avatar answered Sep 20 '22 14:09

Nuno Rafael Figueiredo