Laravel - 使用一对多关系插入多个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21553796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Inserting multiple items using one-to-many relationship
提问by Ashley Banks
Is it possible to insert multiple values through a one-to-many relationship, so that the multiple values are saved with the foreign key.
是否可以通过一对多的关系插入多个值,这样多个值和外键一起保存。
So for example: I have an array of 'contributers' which a user can select to add to a project - upon saving I want these contributers to be referenced to the justsaved project.
例如:我有一组“贡献者”,用户可以选择将其添加到项目中 - 在保存时,我希望将这些贡献者引用到刚刚保存的项目中。
Trying the code below (the array is coming from $_POST['contributers'] which are checkboxes) - it saves the data, but doesn't attach the foreign key. I want to avoid having to use a loop and just be able to bulk insert all of these
尝试下面的代码(数组来自 $_POST['contributers'] 复选框) - 它保存数据,但不附加外键。我想避免使用循环,而只是能够批量插入所有这些
$this->project->find($project->id)
->contributers()
->insert(Input::only('contributers')['contributers']);
回答by Alexandre Butynski
You can use the createMany
method (link to source)
您可以使用该createMany
方法(链接到源)
$project = $this->project->find($project->id);
$project->contributers()->createMany(Input::get('contributers'));
I also propose a small refactoring : one action per line and use of Input::get()
instead of Input:only()
, which is designed for other use cases.
我还提出了一个小的重构:每行一个动作并使用Input::get()
代替Input:only()
,这是为其他用例设计的。