php - 在 Laravel 中插入或更新相关模型(多对多关系)
问题描述
我有这些桌子
products 表、categories 表和 category_products 表(这是前两个表之间的中间表)。
现在,根据 Laravel 文档(Eloquent 关系),它说“通过在连接模型的中间表中插入一条记录来将角色附加到用户,使用附加方法”像这样
$user = App\User::find(1);
$user->roles()->attach($roleId);
在任何情况下,我都是在
产品控制器
为了得到
lastInsertId (我不知道在 laravel 中怎么做),我这样做了
$product_id = $product->save()
然后执行此操作(将每个 category_id 和 product_id 插入到 category_products 表中)
foreach ($this->request->category as $cat)
{
$product_id->categories()->attach($cat, ['product_id' => $product_id]);
}
同时,在
产品型号
类,我有这个方法叫
类别
public function categories()
{
return $this->belongsToMany('Category');
}
因为,根据 laravel doc,它说多对多关系是通过编写一个返回 belongsToMany 方法的结果的方法来定义的。它给出了这个例子
public function roles()
{
return $this->belongsToMany('App\Role');
}
但令我惊讶的是,我收到了这个错误
在布尔值上调用成员函数 categories()
App\Http\Controllers\Admin\ProductsController::store :152 app/Http/Controllers/Admin/ProductsController.php :152
这是
存储()方法
的
产品控制器
public function store()
{
$new = new Product;
$this->request->validate([
'name' => 'bail|required|unique:products|max:100',
'description' => 'required',
'price' => 'required|numeric',
'discounted_price' => 'nullable|numeric',
'display' => 'required',
'stock' => 'required|numeric'
]);
foreach ($this->request->category as $cat)
{
$this->request->validate([
$cat => 'numeric'
]);
}
$new->name = $this->request->name;
$new->description = $this->request->description;
$new->price = $this->request->price;
$new->discounted_price = $this->request->discounted_price;
$new->stock = $this->request->stock;
$new->display = $this->request->display;
$product_id = $new->save();
foreach ($this->request->category as $cat)
{
$product_id->categories()->attach($cat, ['product_id' => $product_id]);// This is the line 152
}
$success = $this->request->session()->flash('status', 'Product was successfully updated!');
return redirect('admin/products')->with($success);
}