您好,我正在嘗試用假數(shù)據(jù)填充我的數(shù)據(jù)庫。為此,我有 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());});當我嘗試建立關(guān)系時,我收到了錯誤general error: 1364 Field 'user_id' doesn't have a default value該關(guān)系不應(yīng)該填充外鍵嗎?// 編輯更多信息患者遷移 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 回答

婷婷同學(xué)_
TA貢獻1844條經(jīng)驗 獲得超8個贊
嘗試以下,它在我的項目中有效。您不能按照您現(xiàn)在的方式使用關(guān)系來創(chuàng)建多個記錄。下面將實現(xiàn)相同的效果。
factory(User::class, 10)->create()->each(function($u) { factory(Patient::class, 10)->create(['user_id' => $u->id]); });
- 1 回答
- 0 關(guān)注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消