首页 > 解决方案 > 如何播种与自身有关系的模型

问题描述

我正在使用 Laravel 8 和 PHP v7.4 我有一个模型,它的模式是通过以下迁移生成的。

创建竞赛表

public function up()
{
    Schema::create('contests', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->foreignId('contest_id')->nullable();
        $table->foreign('contest_id')->references('id')->on('contests');
    });
}

一个contest可以有很多contests。为此,我生成了一个工厂类。

竞赛工厂

public function definition()
{
    return [
        'name' => $this->faker->paragraph(),
    ];
}

比赛播种机

public function run()
{
    \App\Models\Contest::factory(10)->create([
        'contest_id' => array_rand(\App\Models\Contest::all()->pluck('id')->toArray())
    ]);
}

以上引发以下错误。

ErrorException array_rand(): 数组为空

我怎么解决这个问题?

标签: phplaravellaravel-8laravel-seeding

解决方案


当您进行查询以提取信息时,尚未创建记录。您可以create()不带参数调用,以便创建记录,然后您可以迭代返回的集合:

\App\Models\Contest::factory(10)->create()->each(...);

推荐阅读