Wednesday, 9 October 2019

Laravel inserting parent child fails inside transaction

I am trying to perform 2 inserts, in 2 tables table are constrained via a foreign key. These 2 operations must be performed inside a transaction to prevent eventual failures.

The database driver is pgsql.

SomeRepo.php (Tried it with the the transaction closure variant as well)

        DB::beginTransaction();
        try {
            $parentData = [
                'name' => 'Parent name'
            ];
            $parent = new Parent($parentData);
            $parent->save();

            $childData = [
                'parent_id' => $parent->id,
                'name' => 'Child name'
            ];
            $child = new Child($childData);
            $parent->children()->save($child);
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
        }

Parent.php

    protected $fillable = [
        'name'
    ];

    public function children()
    {
        return $this->hasMany(Child::class);
    }

Child.php

    protected $fillable = [
        'name', 'parent_id'
    ];

Execution fails when trying to insert the child row, with the return parent id.

insert or update on table "child" violates foreign key constraint "child_parent_id_foreign"


from Laravel inserting parent child fails inside transaction

No comments:

Post a Comment