如何使用Create function Laravel添加外键日期?

时间:2016-10-23 09:48:35

标签: laravel laravel-5 laravel-5.3

我有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 

1 个答案:

答案 0 :(得分:1)

如果您使用eloquent,则无需手动处理数据透视表。如果您正确设置了关系,则可以改为使用attachsync方法:

在产品中:

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'))
}