Laravel 模型在工厂中播种,列与同一列相关 table
Laravel Model seeding in factory with column related to column on same table
我在 laravel 中植入了一些虚假数据
我有 table
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();
}
);
CategoryFactory
$factory->define(Category::class, function (Faker $faker) {
return [
//'parent_id' => Category::pluck('id')->random(),
'name' => ucfirst($faker->word),
'depth' => 0,
];
});
也许有人可以为相同的结果写出更好的解决方案?我试了很多次,这个有效,但我觉得代码应该比现在看起来更专业。
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]);
}
);
}
我在 laravel 中植入了一些虚假数据 我有 table
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();
}
);
CategoryFactory
$factory->define(Category::class, function (Faker $faker) {
return [
//'parent_id' => Category::pluck('id')->random(),
'name' => ucfirst($faker->word),
'depth' => 0,
];
});
也许有人可以为相同的结果写出更好的解决方案?我试了很多次,这个有效,但我觉得代码应该比现在看起来更专业。
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]);
}
);
}