0
I will put a small example to explain my problem.
Tables:
main
itens
The two have relationship, one main
has several itens
.
What I’m doing to save:
...
$main = $this->main->create($postCreate);
foreach ($postCreate['itens'] as $item){
$item['main_id'] = $main->id;
$this->itens->create($item);
}
...
It works, but if any error occurs when saving the items, is to save the main
without the items or missing some items, wanted to save everything, and if there was any error do not save anything.
How to Save Relationship Tables in Laravel?
Forget the cycle, try
$main->items()->insert($postCreate['itens']);
, you don’t need$item['main_id'] = $main->id
. This code is in the controller?– Miguel
You can use Transactions to do so. Follow the link: Laravel - Database Transactions Thus either all operations will be persisted, or none will be.
– GeekSilva
@Miguel the Insert command worked, however I could not remove the $item['main_id'] = $main->id , and anyway, when the error it saves the main in the same way
– Wictor Chaves
Yes @Geeksilva, well observed, for serious things would have to be just that
– Miguel
@Wictorchaves, in this case transactions are the way. But supposedly you should not enter the
main_id
in the$item
, https://laravel.com/docs/5.6/eloquent-relationships#the-save-method– Miguel
Using the Insert it does not automatically populate the fields created_at updated_at.
– Wictor Chaves
can
createMany
, as there in the Docs they demonstrate– Miguel