Laravel 5:如何根据值 saveMany()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34226203/
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 5: How to saveMany() based on value
提问by user3641381
I need a little help with the following situation.
对于以下情况,我需要一些帮助。
I am willing to saveMany
based on the input value. Let me give code example.
我愿意saveMany
根据输入值。让我给出代码示例。
I was experimenting with the following.
我正在试验以下内容。
$data = [
'id' => 1,
'name' => 'example',
'number_of_slots' => 5,
'material' => 'Colo',
'equipment_status_code_id' => 1,
];
$platecontainer = PlateContainer::create($data);
foreach ($data as $key => $value) {
$platecontainer->containerSlots()->saveMany([
new ContainerSlot([
'plate_container_id' => $data['id'],
'slot' => $data['number_of_slots'],
'occuiped' => false,
])
]);
}
until $platecontainer
everything works just great. What I want is when a PlateContainer
is created using the data
array, I want to create slots as well, but this one is based on number_of_slots
直到$platecontainer
一切正常。我想要的是当PlateContainer
使用data
数组创建a 时,我也想创建插槽,但这个是基于number_of_slots
So for instance number_of_slots
in the example is 5
so I want to save 5
records in (descendingorder) in the ContainerSlot
table
因此,例如number_of_slots
在示例中5
,我想在表中5
以(降序)保存记录ContainerSlot
so the containerslots table will end up looking something like this.
所以 containerlots 表最终会看起来像这样。
回答by Steve Bauman
The save many method accepts an array of models, so just use a for
loop for the $plateContainer
's number_of_slots
save many 方法接受一个模型数组,所以只需for
对$plateContainer
's使用循环number_of_slots
$plateContainer = PlateContainer::create($data);
$containers = [];
// Need to add one to our number of slots because
// the $i count starts at one instead of zero.
$slots = $plateContainer->number_of_slots + 1;
for($i = 1; $i < $slots; $i++) {
$containers[] = new ContainerSlot([
'plate_container_id' => $plateContainer->getKey(),
'slot' => $i,
'occuiped' => false,
]);
}
$plateContainer->containerSlots()->saveMany($containers);