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

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

问题描述

我正在创建一个围绕食物过敏的数据库,我在食物和过敏之间建立了多对多的关系.还有一个名为 severity 的枢轴值,它有一个数字表示该食品的过敏严重程度.

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.

这个链接表是这样的;

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

问题

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

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

如何将多个值与数据透视表一起一次添加到该数据透视表?

How would I go about adding multiple values to this pivot table at once along with the pivot values?

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

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

对特定食物可能有 0 到 20 种过敏,每种过敏的严重程度等级为 0 到 4,如果这有帮助的话.

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.

推荐答案

你可以.

来自文档中的这个示例(4.25.0):

From this example in Docs (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 处于兼容状态(大小和排序)时,您应该事先准备好同步数据.类似的东西:

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天全站免登陆