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.
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);
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.
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.
You can use createMany (array of arrays of attributes) instead of saveMany (array of models new or existing). Useful for API calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With