[英]Laravel - Inserting multiple items using one-to-many relationship
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 just saved 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. 尝试下面的代码(该数组来自复选框的$ _POST ['contributers'])-保存数据,但不附加外键。 I want to avoid having to use a loop and just be able to bulk insert all of these
我想避免不得不使用循环,而只是能够批量插入所有这些
$this->project->find($project->id)
->contributers()
->insert(Input::only('contributers')['contributers']);
You can use the createMany
method ( link to source ) 您可以使用
createMany
方法( 链接到source )
$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()
,后者是为其他用例设计的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.