user3641381
user3641381

Reputation: 1076

Laravel 5: How to saveMany() based on value

I need a little help with the following situation.

I am willing to saveMany based on the input value. Let me give code example.

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

So for instance number_of_slots in the example is 5 so I want to save 5 records in (descending order) in the ContainerSlot table

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

enter image description here

Upvotes: 11

Views: 23671

Answers (3)

Bitclaw
Bitclaw

Reputation: 831

You can use createMany (array of arrays of attributes) instead of saveMany (array of models new or existing). Useful for API calls.

Upvotes: 4

JCarlosR
JCarlosR

Reputation: 1663

An alternative, if you want to insert data based on value, you can prepare your array and let the model insert in bulk.

$itemRebates = array_map(function ($rebateId) use ($payoutItem) {
    return [
        'rebate_id' => $rebateId,
        'payout_item_id' => $payoutItem->id
    ];
}, $rebateIds);

PayoutItemRebate::insert($itemRebates);

This way you don't need to wrap your data in multiple model instances.

Additional details

I tried to use the insert method from $payoutItem->historyRebates() but it didn't take the payout_item_id from the relationship. So it's better to use the model itself.

My first attempt was to use saveMany, but even preparing the data, it doesn't work with arrays, only with model instances. I wanted to avoid that.

Upvotes: 1

Steve Bauman
Steve Bauman

Reputation: 8688

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

Upvotes: 10

Related Questions