您好,我正在尝试用假数据填充我的数据库。
为此,我有 2 个模型:用户和患者。
在用户.php中
public function patients()
{
return $this->hasMany(Patient::class);
}
在Patient.php中
public function user()
{
return $this->belongsTo(User::class);
}
我的 DatabaseSeeder.php
$users = factory(User::class, 10)->create();
$users->each(function ($user) {
$user
->patients()
->saveMany(factory(Patient::class, 10)
->create());
});
当我尝试建立关系时,我收到了错误
general error: 1364 Field 'user_id' doesn't have a default value
该关系不应该填充外键吗?
// 编辑更多信息患者迁移
if (Schema::hasTable($this->setSchemaTable)) return;
Schema::create($this->setSchemaTable, function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('firstname', 191);
$table->string('lastname', 191);
$table->date('birth_date');
$table->nullableTimestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users');
});
病人工厂
$factory->define(Patient::class, function (Faker $faker) {
return [
'firstname' => $faker->firstname,
'lastname' => $faker->lastname,
'birth_date' => $faker->date,
];
});
用户迁移
if (Schema::hasTable($this->setSchemaTable)) return;
Schema::create($this->setSchemaTable, function (Blueprint $table) {
$table->increments('id');
$table->string('firstname', 191);
$table->string('lastname', 191);
$table->string('email', 191)->unique();
$table->string('password', 191);
$table->rememberToken();
$table->string('lang')->default('en');
$table->tinyInteger('change_password')->default('1');
$table->softDeletes();
$table->nullableTimestamps();
});
婷婷同学_