简体   繁体   English

Laravel:编辑一对多关系字段

[英]Laravel: Editing one-to-many relationship fields

I have a table structure similar to this: 我有一个类似于此的表结构:

id   name   superpower
 1     A      speed
 2     A      stamina
 3     B      speed
 4     C      power
 5     B      power
 6     D      sarcasm

Name has a one-to-many relationship to Superpower. Name与Superpower有一对多关系。 To edit these fields, the front-end form returns an array of superpowers for the name. 要编辑这些字段,前端表单将为该名称返回一个超能力数组。 Ie, the 'edit A' form could return ['speed','power'] (removing stamina and adding power). 也就是说,“ edit A”表格可以返回['speed','power'] (消除耐力并增加力量)。

An easy way to do this with pure PHP is to remove all superpowers of the name and add the new ones. 使用纯PHP做到这一点的一种简单方法是删除名称的所有超级能力并添加新的超级能力。 What is the best way to do this in Laravel? 在Laravel中执行此操作的最佳方法是什么?

So you have a User model (for auth), a Kid model for the details of the kids, and then Superpower model for the details of the superpowers. 因此,您有一个User模型(用于auth),一个Kid模型用于孩子的详细信息,然后是Superpower模型,用于超级电源的详细信息。

You have two options that I see. 我有两种选择。 Option one requires a bigger structural change, but easier controller logic while the other is heavier in the controller. 选项一需要进行较大的结构更改,但控制器逻辑更容易,而另一种则在控制器中较重。

1 - 1-

Create a many-to-many relationship with the kids and superpowers. 与孩子和超级大国建立多对多关系。 This may not fit your use case if the users can add new superpowers that are viewable to all other users. 如果用户可以添加对所有其他用户可见的新超级能力,则这可能不适合您的用例。 This would involve a pivot table that would store each connection between a kid and a superpower. 这将涉及一个数据透视表,该数据透视表将存储孩子和超级大国之间的每个联系。

When returning an array of superpowers to link to a kid (let's say a checkbox list is being submitted in a form), you can use the relationships' sync method: 当返回一个超能力数组以链接到孩子时(假设正在以表单形式提交复选框列表),可以使用关系的sync方法:

$kid->superpowers->sync($superpowers);

2 - 2-

If you want to keep your relationships basically how they are, I recommend at least changing the table structure you proposed in your question so that the name field is kid_id . 如果要基本保持关系的状态,建议至少更改问题中建议的表结构,以使name字段为kid_id This would be more standard so that a kid would have a hasMany relationship to superpowers and a superpower would have a belongsTo with a kid. 这将是更标准的,这样一个孩子将与超级大国有hasMany关系,而一个超级大国将与一个小孩子拥有belongsTo。

Then you could call: 然后您可以致电:

foreach ($request->superpowers as $superpower) {
    $superpowers[] = ['superpower' => $superpower];
}

$kid->superpowers->delete();
$kid->superpowers->createMany($superpowers);

A noticable downside to this approach is that the data is being removed first in order to sync. 这种方法的明显缺点是,为了同步,首先要删除数据。 The resulting created_at timestamps would then be incorrect. 生成的created_at时间戳将不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM