我以为我在开发Laravel技能方面做得很好,但是似乎我陷入了困境,无法在线找到解决方案。
我的项目是在Laravel和Vue中建立的,我正在尝试存储包含成分的产品。产品在产品表中。成分表中的成分。我成功地使用brand_id存储了产品,后来又检索了品牌(一对多),但是我不知道如何进行多对多的操作:产品的成分。
由于我正在使用Vue,所以我添加了发布数据的JSON输出。
public function store()
{
$product = new Product();
$product->ean = request('ean');
$product->name = request('productName');
$product->brand_id = request('brandId');
$ingredients = request('ingredients');
$product->save();
}
正如我上面解释的,保存产品进展顺利。 但是现在我需要对$ ingredients数组做些事情,我发现了类似以下的行:
$user->roles()->save($role);
所以我认为我必须对所有成分进行一次foreach循环,并在其中进行以下操作:
$product->ingredients()->save($ingredient);
我不明白的内容。该数组将包含已经存储的现有成分,还必须将新成分添加到成分表中。如何进行这项工作?
因此,将新成分存储在表中,并将关系存储在雄辩的表中。我可能很近,我可能很远,有人吗?
答案 0 :(得分:1)
在循环配料时,请查看firstOrNew()
方法:
foreach($request->input("ingredients") AS $ingredient){
$ingredient = Ingredient::firstOrNew(["name" => $ingredient]);
// Note: assumed name for column that matches `$ingredient` from array, adjust as needed.
}
在该循环中,将attach()
$ingredient
切换到新的$product
。完全实现后,您的代码应如下所示:
$product = new Product();
...
$product->save();
foreach($request->input("ingredients") AS $ingredient){
$ingredient = Ingredient::firstOrNew(["name" => $ingredient]);
$product->ingredients()->attach($ingredient->id);
}
attach()
通过将记录添加到$ingredient
和$product
之间的数据透视表中,将这个新的或现有的Product
与新的Ingredient
关联。无法使用$product->ingredients()->save($ingredient);
的原因是这是many-to-many
,需要attach()
。 $model->relationship()->save();
用于one-to-many
。
有关创建方法的完整文档,请参见:https://laravel.com/docs/5.8/eloquent#other-creation-methods