【问题标题】:Laravel 8 Seeders: Property [id] does not exist on this collection instanceLaravel 8 Seeders:此集合实例上不存在属性 [id]
【发布时间】:2021-11-14 07:19:39
【问题描述】:

我想为表 userscourses 和 `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


【解决方案1】:

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

$user = User::all();

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

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2021-09-05
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多