Laravel将枢轴连接到具有多个值的表 [英] Laravel attach pivot to table with multiple values

查看:138
本文介绍了Laravel将枢轴连接到具有多个值的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景



我正在创建一个围绕食物过敏的数据库,我与食物和过敏有许多关系。还有一个称为严重性的枢轴值,它具有代表该食品过敏严重程度的数字。



此链接表如下所示:

  food_id | allergy_id | severity 
------- | ---------- | --------
1 | 1 | 3
1 | 4 | 1
2 | 2 | 1



问题



用Eloquent更新链接表(其中 $ allergy_ids 是一个数组)

  $食品 - >过敏() - >附加($ allergy_ids); 

我将如何一起添加多个值与这个数据透视表一起以及透视值? / p>

我可以使用上述一行添加一个特定食品的所有 allergy_id ,但如何我还可以使用各种严重性值的数组同时添加严重性列?也许像

  $ food-> allergies() - > attach($ allergy_ids,$ severity_ids); 

编辑:特定食品可能有0-20个过敏, 0-4每个过敏,如果这有帮助。

解决方案

你可以。



从文档中的此示例( 4.2 5.0 ):

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

前两行的硬编码版本:

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

动态地,您的数组$ allergy_ids和$ severities处于兼容状态(大小和排序),您之前准备你的同步数据。如下所示:

  $ sync_data = []; ($ i = 0; $ i< count($ allergy_ids); $ i ++)
$ sync_data [$ allergy_ids [$ i]] = ['severity'=> $严重性[$ I]];

$ food-> allergies() - > sync($ sync_data);


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.

解决方案

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);

这篇关于Laravel将枢轴连接到具有多个值的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆