Laravel模型在工厂中进行播种,其中列与同一表上的列相关

时间:2019-05-02 18:04:12

标签: laravel each factory seeding faker

我正在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必须包含category.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();
        }
);
  

CategoryFactory

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

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

1 个答案:

答案 0 :(得分:1)

2019_05_03 _ ****** _ create_categories_table.php

<asp:HyperLinkField DataNavigateUrlFields="DosyaAdresi" DataNavigateUrlFormatString="dosyalar\{0}" DataTextField="DosyaAdresi" HeaderText="DosyaAdresi" DataTextFormatString="DosyaAdresi" Text="DosyaAdresi" >

CategoryFactory.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();
});

CategoriesTableSeeder.php

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