How to save relationship tables in Laravel?

Asked

Viewed 187 times

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?

  • You can use Transactions to do so. Follow the link: Laravel - Database Transactions Thus either all operations will be persisted, or none will be.

  • @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

  • Yes @Geeksilva, well observed, for serious things would have to be just that

  • @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

  • Using the Insert it does not automatically populate the fields created_at updated_at.

  • can createMany, as there in the Docs they demonstrate

Show 2 more comments

1 answer

0


I decided as follows

I imported the following class:

use Illuminate\Support\Facades\DB;

And I put my code inside transaction:

return DB::transaction(function () use ($campos){
    return $this->meuMetodo($campos);
});

This way all transactions that are within meuMetodo will only be truly saved if all give true.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.