我在一個更大的項目上工作,我們在一個Postgres數據庫中有多個模式。我們在模式之間創建了外鍵。這裏是一個例子> 我們有公司架構和用戶架構。公司架構具有company_users表這對user.users表的外鍵約束Laravel 5.3雄辯的交易和外鍵約束
CREATE TABLE company.company_user
(
id serial NOT NULL,
company_id integer NOT NULL,
user_id integer NOT NULL,
created_at timestamp(0) without time zone,
updated_at timestamp(0) without time zone,
deleted_at timestamp(0) without time zone,
CONSTRAINT company_user_pkey PRIMARY KEY (id),
CONSTRAINT company_user_company_id_foreign FOREIGN KEY (company_id)
REFERENCES company.companies (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT company_user_user_id_foreign FOREIGN KEY (user_id)
REFERENCES "user".users (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
繼Postgres的沒有問題,運行
BEGIN;
insert into "db"."user"."users" (id,"surname", "firstname", "email", "position", "language_id", "is_super_admin", "updated_at", "created_at") values (156,'Mueller', 'Julianne', '[email protected]', 'Nuclear Power Reactor Operator', 41, false, '2017-01-13 12:35:10', '2017-01-13 12:35:10') returning "id";
insert into "db"."company"."company_user" ("company_id", "user_id", "updated_at", "created_at") values (4445, 156, '2017-01-13 12:35:10', '2017-01-13 12:35:10') returning "id";
COMMIT;
但是查詢,如果我在Laravel
\DB::beginTransaction();
$user = new User(["surname" => 'Mueller',
"firstname" => 'Julianne',
"email" => '[email protected]',
"position" => 'Nuclear Power Reactor Operator',
"language_id" => 41,
"is_super_admin" => false]
);
if (!$user->save()) {
\DB::rollBack();
return false;
}
\Log::error($user->id);
$company_user = new CompanyUser([
"company_id" => 4445,
"user_id" => $user->id
]);
if (!$company_user->save()) {
\DB::rollBack();
return false;
}
\DB::commit();
通過雄辯執行相同的查詢
正在拋出以下錯誤(它似乎無法在表中找到用戶的ID)
PDOException: SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "company_user" violates foreign key constraint "company_user_user_id_foreign"
會有人會說爲什麼這不起作用嗎? \ Log :: error($ user-> id)是插入用戶的打印ID。我試圖使用DB監聽器打印來自Laravel的查詢,所有查詢都按正確的順序執行,但仍然出現此錯誤。
嘿阿列克謝。比這更復雜一點。是companyUser有兩個設置爲可填充的,那裏有一小段代碼,在用戶被保存之後調用\ Log :: error($ user-> id),並且在日誌中獲得id,所以看起來Eloquent正在保存那一排。即使我試圖傾聽數據庫查詢,他們都以正確的順序運行,例如,首先插入到用戶表中,然後插入公司用戶,但仍然是相同的錯誤 – Lukas
您是否試圖在沒有事務的情況下執行此操作? –
沒有交易它正在工作,但我需要交易這些類型的查詢。這僅僅是一個例子。但是我將調用不同的API,當其中一個失敗時,我需要將所有更改恢復回來。 – Lukas