-1

我想为表格和`episodes 运行users播种机courses

这里是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 ])at 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();
        });
    }

此外,如果您需要查看任何其他迁移或模型代码,请告诉我,我会立即添加它们。

4

1 回答 1

0

问题可能出在模型的导入上。导入用户模型并执行类似的操作

$user = User::all();

在工厂上方你必须初始化变量

于 2021-09-21T10:11:12.733 回答