我有product
表和product_category
表。
我将新产品添加为:
$product = Product::create($data);
尝试为此添加产品添加类别后:
$category = new ProductCategoryItem();
$category->category_id = $request->parent_id;
$category->product_id = $product->id;
$category->save();
但它给了我SQL错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
答案 0 :(得分:1)
如果您使用eloquent
,则无需手动处理数据透视表。如果您正确设置了关系,则可以改为使用attach
或sync
方法:
在产品中:
public function categoryItems(){
// use withTimestamps if you have timestamps in your pivot table
return $this->belongsToMany('App\CategoryItem')->withTimestamps();
}
在CategoryItem中:
public function products(){
return $this->hasMany('App\Product');
}
在您的产品控制器中:
public function store(Request $request){
$product = Product::create($request->all());
// Assumes you have an array input in your form called 'categories'
$product->categoryItems()->attach($request->input('categories'))
}