如何从 Create 函数 Laravel 添加带有外键的日期?
How to add date with foreign key from Create function Laravel?
我有 product
table 和 product_category
table。
我将新产品添加为:
$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
如果您使用 eloquent
,则无需手动处理枢轴 table。如果您正确设置了关系,则可以改用 attach
或 sync
方法:
在产品中:
public function categoryItems(){
// use withTimestamps if you have timestamps in your pivot table
return $this->belongsToMany('App\CategoryItem')->withTimestamps();
}
在类别项目中:
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'))
}
我有 product
table 和 product_category
table。
我将新产品添加为:
$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
如果您使用 eloquent
,则无需手动处理枢轴 table。如果您正确设置了关系,则可以改用 attach
或 sync
方法:
在产品中:
public function categoryItems(){
// use withTimestamps if you have timestamps in your pivot table
return $this->belongsToMany('App\CategoryItem')->withTimestamps();
}
在类别项目中:
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'))
}