【发布时间】:2020-04-05 09:51:38
【问题描述】:
我在使用工厂时遇到了问题 对于一对多关系中的三个嵌套级别 这些是我的迁移:
Schema::create('main_categories', function (Blueprint $table) {
$table->id();
$table->string('name', 100)->nullable(false);
});
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name', 100)->nullable(false);
$table->unsignedBigInteger('main_category_id');
$table->foreign('main_category_id')
->references('id')
->on('main_categories')
->cascadeOnDelete();
});
Schema::create('sub_categories', function (Blueprint $table) {
$table->id();
$table->string('name', 100)->nullable(false);
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')
->references('id')
->on('categories')
->cascadeOnDelete();
});
这些是我的模型
class MainCategory extends Model
{
...
public function categories()
{
return $this->hasMany(Category::class);
}
}
class Category extends Model
{
...
public function MainCategory()
{
return $this->belongsTo(MainCategory::class);
}
public function subCategories()
{
return $this->hasMany(SubCategory::class);
}
}
class SubCategory extends Model
{
...
public function category()
{
return $this->belongsTo(Category::class);
}
public function products()
{
return $this->hasMany(Product::class);
}
}
这些是我的工厂:
$factory->define(MainCategory::class, function (Faker $faker) {
return [
'name'=>$faker->name
];
});
$factory->define(Category::class, function (Faker $faker) {
return [
'name' => $faker->name
];
});
$factory->define(SubCategory::class, function (Faker $faker) {
return [
'name' => $faker->name
];
});
我就这样使用这些工厂。我应该说,我想在创建 MainCategory 行时,立即创建 Category 如何与 MainCategory 有一对多关系,然后 SubCategory 应该创建如何与 Category 有一对多关系。 我不知道我的错误在哪里:
factory(MainCategory::class, 5)->create()->each(function ($mainCategory) {
$mainCategory->categories()->saveMany(factory(Category::class, 7)->make()->each(function ($category){
$category->subCategories()->saveMany(factory(SubCategory::class, 7)->make());
}));
});
【问题讨论】: