Laravel模型在工厂中播种,列与同一表中的列相关
我在拉威尔播了一些假数据 我有一张桌子Laravel模型在工厂中播种,列与同一表中的列相关,laravel,each,factory,seeding,faker,Laravel,Each,Factory,Seeding,Faker,我在拉威尔播了一些假数据 我有一张桌子 Schema::create('categories', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('parent_id')->default(0); $table->string('name'); $table->integer('depth');
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('parent_id')->default(0);
$table->string('name');
$table->integer('depth');
$table->timestamps();
});
父id必须包含categories.id的数据
我想知道这是最好的方法吗
可分级播种机
分类工厂
也许有人能为同样的结果写出更好的解决方案?我尝试了很多,这一个很有效,但我认为代码应该比现在看起来更专业。2019\u 05\u 03\u*****\u create\u categories\u 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]);
}
);
}
$factory->define(Category::class, function (Faker $faker) {
return [
'parent_id' => Category::count() ? Category::pluck('id')->random() : 0,
'name' => ucfirst($faker->word),
];
});
public function run()
{
factory(Category::class, rand(1, 10))->create()->each(
function ($category) {
factory(Category::class, rand(1, 5))->create(['parent_id' => $category->id]);
}
);
}