我正在使用 MySQL 8.0 在 PHP 7.4 上运行 Laravel 7。
我有三个表,User和Company,Department以及它们各自的模型和工厂。
我创建了一个要添加关系的测试:
// MyTest.php
$user = factory(User::class)->create();
$company = factory(Company::class)->make();
$company->user()->associate($user);
$company->create(); // it fails here because of NOT NULL constraint, companies.user_id
$department = factory(Department::class)->make();
$department->company()->associate($company);
$department->create();
我收到以下错误:Integrity constraint violation: 19 NOT NULL constraint failed: companies.user_id (SQL: insert into "companies" ("updated_at", "created_at") values (2020-03-10 07:27:51, 2020-03-10 07:27:51))
我的表模式定义如下:
// users
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone');
$table->integer('user_type');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
// companies
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('contact_email');
$table->string('contact_phone');
$table->timestamps();
});
// departments
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->foreignId('company_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('contact_email');
$table->string('contact_phone');
$table->timestamps();
});
->nullable()我的理解是 SQL 表中不应该有 NULL 值,这就是为什么我在迁移中刻意避免使用的原因。特别是对于像这样的外键。
慕标琳琳