Laravel 8使用工厂播种机向数据透视表添加数据



我有产品和类别模型,我用一个名为Category_Product的数据透视表创建了多对多关系。

我还创建了2个类别和产品工厂。

我正在尝试添加100种产品,每个产品有2个类别。不知怎么的,它在我的分类表上广告了200张唱片。我做错了什么?

我的类别工厂类别:

public function definition()
{
return [
'name' => $this->faker->numberBetween(1, 12),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
];
}

我的ProductFactory类看起来是这样的:

public function definition()
{
return [
'name' => $this->faker->name,
'description' => $this->faker->text,
'image' => 'image-' . rand(1, 10) . '.jpg',
'price' => $this->faker->numberBetween(300, 20000),
'code' => $this->faker->regexify('[A-Z0-9]{12}'),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
];
}

我的ProductSeeder 中有这些

Product::factory(100)->has(Category::factory()->count(2))->create();

我的数据透视表迁移:

Schema::create('category_product', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained();
$table->foreignId('category_id')->constrained();
$table->timestamps();
});

在你的工厂播种机中,你本质上是在说">为每个产品创建两个新类别,然后将它们链接到产品";,这就是为什么你最终会有200个类别。如果您查看透视表,您会发现您也有200个条目,但没有一个category_id是相同的。

如果,我假设,你想要100种产品,2个类别和它们之间的联系,你的播种机应该更像

$categories= Category::factory()->count(2)->create();
$products = Product::factory()
->count(100)
->hasAttached($categories)
->create();

您将得到100个产品、2个类别和200个数据透视条目,其中category_id的基数为2(即id 1和2(

最新更新