我正在尝试执行 2 次插入,在 2 个表中,表受外键约束。这两个操作必须在事务中执行以防止最终失败。(实际上我需要在更多表上执行更多插入,因此事务很重要;但此示例中的 2 个表足以复制问题)
数据库驱动是pgsql
SomeRepo.php(也尝试了事务关闭变体)
DB::beginTransaction();
try {
$parentData = [
'name' => 'Parent name'
];
$parent = new Parent($parentData);
$parent->save();
$childData = [
// Tried it with and without setting "parent_id" here
'parent_id' => $parent->id,
'name' => 'Child name'
];
$child = new Child($childData);
$parent->children()->save($child);
DB::commit();
} catch (Exception $e) {
DB::rollback();
}
父.php
protected $fillable = [
'name'
];
public function children()
{
return $this->hasMany(Child::class);
}
儿童.php
protected $fillable = [
'name', 'parent_id'
];
尝试插入子行时执行失败,返回父 ID。
insert or update on table "child" violates foreign key constraint "child_parent_id_foreign"
Smart猫小萌
倚天杖
烙印99