Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: How to saveMany() based on value

Tags:

php

laravel

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

like image 314
user3641381 Avatar asked Dec 11 '15 14:12

user3641381


3 Answers

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);
like image 160
Steve Bauman Avatar answered Oct 03 '22 17:10

Steve Bauman


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.

like image 45
JCarlosR Avatar answered Oct 03 '22 15:10

JCarlosR


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

like image 25
Bitclaw Avatar answered Oct 03 '22 16:10

Bitclaw