【发布时间】:2020-01-24 04:21:01
【问题描述】:
我正在尝试执行 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();
}
Parent.php
protected $fillable = [
'name'
];
public function children()
{
return $this->hasMany(Child::class);
}
Child.php
protected $fillable = [
'name', 'parent_id'
];
尝试插入子行时执行失败,返回父 ID。
insert or update on table "child" violates foreign key constraint "child_parent_id_foreign"
编辑 子表SQL:
DROP TABLE IF EXISTS "public"."child";
CREATE TABLE "public"."child" (
"id" int4 NOT NULL DEFAULT nextval('child_id_seq'::regclass),
"parent_id" int4 NOT NULL,
"is_read" bool NOT NULL DEFAULT false,
"created_at" timestamp(0) DEFAULT now(),
"updated_at" timestamp(0),
"deleted_at" timestamp(0)
)
;
ALTER TABLE "public"."child" OWNER TO "my_user";
-- ----------------------------
-- Primary Key structure for table child
-- ----------------------------
ALTER TABLE "public"."child" ADD CONSTRAINT "child_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Foreign Keys structure for table child
-- ----------------------------
ALTER TABLE "public"."child" ADD CONSTRAINT "child_parent_id_fkey" FOREIGN KEY ("parent_id") REFERENCES "public"."parent" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION DEFERRABLE INITIALLY DEFERRED;
【问题讨论】:
-
你能告诉我们数据库的结构吗?
-
我认为这是在 postgreSql 中插入具有循环引用的表的先有鸡还是先有蛋的问题
-
尝试在 ->save() 之后转储 $parent->id... 确保数据确实存在。
-
stackoverflow.com/a/41715578/2693543,请阅读此问题的评论
标签: php laravel postgresql transactions foreign-keys