【问题标题】:Laravel Model seeding in factory with column related to column on same tableLaravel 模型在工厂播种,列与同一表上的列相关
【发布时间】:2019-09-21 07:11:42
【问题描述】:

我在 laravel 中植入了一些虚假数据 我有桌子

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('parent_id')->default(0);
        $table->string('name');
        $table->integer('depth');
        $table->timestamps();
 });

parent_id 必须包含 categories.id 的数据

我想知道这是最好的方法吗?

CategoriesTableSeeder

factory(App\Category::class, 10)->make()->each(
        function ($c) {
            $c->fill(
                [
                    'parent_id' => App\Category::count() ? App\Category::pluck('id')->random() : 0
                ]
            )->save();
        }
);

类别工厂

$factory->define(Category::class, function (Faker $faker) {
    return [
        //'parent_id' => Category::pluck('id')->random(),
        'name' => ucfirst($faker->word),
        'depth' => 0,
    ];
});

也许有人可以为相同的结果编写更好的解决方案?我尝试了很多,这个可行,但我认为代码应该比现在看起来更专业。

【问题讨论】:

    标签: laravel each factory seeding faker


    【解决方案1】:

    2019_05_03_******_create_categories_table.php

    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('parent_id')->default(0);
        $table->string('name')->nullable();
        $table->integer('depth')->default(0);
        $table->timestamps();
    });
    

    CategoryFactory.php

    $factory->define(Category::class, function (Faker $faker) {
        return [
            'parent_id' => Category::count() ? Category::pluck('id')->random() : 0,
            'name' => ucfirst($faker->word),
        ];
    });
    

    CategoriesTableSeeder.php

    public function run()
    {
        factory(Category::class, rand(1, 10))->create()->each(
            function ($category) {
                factory(Category::class, rand(1, 5))->create(['parent_id' => $category->id]);
            }
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 2021-06-11
      • 1970-01-01
      • 2017-11-24
      • 2017-08-02
      • 2015-09-16
      • 2016-02-26
      • 1970-01-01
      相关资源
      最近更新 更多