为了账号安全,请及时绑定邮箱和手机立即绑定

使用关系时缺少外键

使用关系时缺少外键

PHP
慕侠2389804 2023-11-03 15:46:02
您好,我正在尝试用假数据填充我的数据库。为此,我有 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();        });
查看完整描述

1 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

尝试以下,它在我的项目中有效。您不能按照您现在的方式使用关系来创建多个记录。下面将实现相同的效果。

factory(User::class, 10)->create()->each(function($u) {
    factory(Patient::class, 10)->create(['user_id' => $u->id]);
});


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信