我在laravel中的数据透视表遇到问题,我有一个Product
,Category
表和一个category_product
pivit表,定义如下:
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->integer('product_id')->unsigned();
});
然后在我的产品分类中
public function categories()
{
return $this->belongsToMany(Category::class);
}
以及类别类别
中public function products()
{
return $this->belongsToMany(Product::class);
}
当我尝试这样做
$product->categories()->attach(Category::find([3,4]));
这种行为有点可笑 首先只有一个类别被附加,当我再试一次时,我收到一个mysql错误
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY' (SQL: insert into `category_product` (`category_id`, `id`, `product_id`) values (0, 3, 2), (1, 4, 2))
答案 0 :(得分:1)
您可以像这样使用'newPivotQuery':
$product->categories()->newPivotQuery()->insert([
['category_id'=>3,'product_id'=>$product->id],
['category_id'=>4,'product_id'=>$product->id]
]);
newPivotQuery()允许您直接在数据透视表上进行查询