dimanche 14 juin 2020

Transaction across multiple Eloquent Models using Laravel 5.1

I want to insert a parent item and all of it's childs into a database. If any of the childs fails to create I'd like to abort the entire transaction.

I've tried using the following snippet:

DB::beginTransaction();

try
{
    // Create parent item
    $one = new ModelOne();
    $one->key = 'Parent Key';
    $one->title = 'Parent title';
    $one->save();

    // Create child items
    foreach ($items as $item) {
        $two = new ModelTwo();
        $two->parent_id = $one->id;
        $two->content = $item->content;
        $two->status = $item->status;
        $two->save();
    }

    DB::commit();
    return response(['message'=>'ALL GOOD'], 200);
}
catch (\ Illuminate\Database\QueryException $e)
{
    DB::rollBack();
    return response(['message'=>'FAILURE'], 500);
}

However, when an exception is thrown (say because a key is duplicated among the childs) ModelOne ($one) is saved in the database even though DB::commit() is never called.

What am I missing?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire