Laravel 5.3雄辩交易和外键限制

时间:2017-01-13 13:55:42

标签: postgresql laravel transactions eloquent foreign-keys

我正在开发一个更大的项目,我们在一个Postgres数据库中有多个模式。我们在模式之间创建了外键。这是一个例子> 我们有公司架构和用户架构。公司模式有company_users表,对user.users表有外键限制

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', 'julianne.mueller1@example.org', '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中通过Eloquent执行相同的查询

\DB::beginTransaction();
$user = new User(["surname" => 'Mueller',
                  "firstname" => 'Julianne',
                  "email" => 'julianne.mueller1@example.org',
                  "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。我尝试使用数据库侦听器从Laravel打印出查询,所有查询都按正确顺序执行,但仍然出现此错误。

2 个答案:

答案 0 :(得分:1)

确保CompanyUser$fillable

$fillable = ['user_id', 'company_id'];

此外,请确保具有此ID的用户已在users表中。也许你需要摆脱交易。

答案 1 :(得分:0)

好的,我们找到了解决方案。看来我们需要分别为每个模式启动事务+引用不同模式的每个外键应该创建为延迟模式。