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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:48:12  来源:igfitidea点击:

Laravel 5: How to saveMany() based on value

phplaravel

提问by user3641381

I need a little help with the following situation.

对于以下情况,我需要一些帮助。

I am willing to saveManybased 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 $platecontainereverything works just great. What I want is when a PlateContaineris created using the dataarray, 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_slotsin the example is 5so I want to save 5records in (descendingorder) in the ContainerSlottable

因此,例如number_of_slots在示例中5,我想在表中5以(降序)保存记录ContainerSlot

so the containerslots table will end up looking something like this.

所以 containerlots 表最终会看起来像这样。

enter image description here

在此处输入图片说明

回答by Steve Bauman

The save many method accepts an array of models, so just use a forloop 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);