【发布时间】:2021-11-14 07:19:39
【问题描述】:
我想为表 users、courses 和 `episodes 运行播种器。
这里是UserFactory:
public function definition()
{
static $password;
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => Str::random(10),
];
}
这里是EpisodeFactory:
public function definition()
{
return [
'title' => $this->faker->sentence(),
'body' => $this->faker->paragraph(5),
'videoUrl' => 'https://www.quirksmode.org/html5/videos/big_buck_bunny.mp4',
];
}
这是CourseFactory:
public function definition()
{
return [
'title' => $this->faker->sentence(),
'body' => $this->faker->paragraph(5),
'price' => $this->faker->numberBetween(1000,10000),
'image' => $this->faker->imageUrl(),
];
}
然后我将此添加到DatabaseSeeder:
public function run()
{
$user = \App\Models\User::factory()->count(30)->create();
\App\Models\Course::factory()->count(5)->create(['user_id' => $user->id ])->each(function ($course) {
\App\Models\Episode::factory()->count( rand(6 , 20))->make()->each(function ($episode , $key) use ($course){
$episode->number = $key +1;
$course->episodes()->save($episode);
});
});
}
现在当我运行 php artisan db:seed 时,我得到了这个错误:
异常此集合实例上不存在属性 [id]。
这是指create(['user_id' => $user->id ])DatabaseSeeder。
那么这里出了什么问题?我该如何解决这个问题?
这里也是users表的迁移:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
另外,如果您需要查看其他迁移或模型代码,请告诉我,我会立即添加。
【问题讨论】:
-
你正在创建 30 个用户,
id应该神奇地知道用作$user->id? -
@BrianThompson 我不明白。我应该怎么做才能解决这个问题?
-
$user = \App\Models\User::factory()->count(30)->create()创建 30 个用户对吗?count(30)指示它。这意味着$user不包含 顾名思义,它包含所有 30 个用户的集合。所以$user->id没有意义,因为有 30 个 id。您将不得不以某种方式选择其中一个 ID。我不能说怎么做,因为我不知道你想要完成什么
标签: php laravel laravel-8 laravel-seeding laravel-factory