【问题标题】:Laravel Many-To-Many relationship with multiple functionsLaravel 与多个函数的多对多关系
【发布时间】:2019-11-08 20:03:12
【问题描述】:

我以为我在开发 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);

我无法理解的内容。该数组将包含已存储的现有成分,但也包含必须添加到成分表中的新成分。如何使这项工作?

所以将新成分存储在它的表中,并将关系存储在 eloquent 表中。我可能很近,我可能很远,有人吗?

【问题讨论】:

    标签: laravel vue.js eloquent many-to-many laravel-controller


    【解决方案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 相关联,方法是将记录添加到ProductIngredient 之间的枢轴。不能使用$product->ingredients()->save($ingredient); 的原因是这是一个many-to-many,它需要attach()$model->relationship()->save(); 用于one-to-many

    关于创建方法的完整文档可以在这里找到:https://laravel.com/docs/5.8/eloquent#other-creation-methods

    【讨论】:

    • 他也可以在第一个循环中使用 firstOrNew,然后将检索/插入成分的 Id 值放入 $ingredients 并使用 foreach 之外的$product->ingredients()->sync($ingredients)); 大量同步关系跨度>
    • 感谢您的回答。它似乎帮助我更进一步。现在有一个新错误,似乎没有通过 attach() 调用发送的产品 ID:SQLSTATE[23000]:完整性约束违规:1048 列“product_id”不能为空(SQL:插入product_ingredientsingredient_idproduct_id) values (2, )) 编辑:Nvm,必须在我的 foreach 之前放置 $product->save()
    • 哦,顺便说一句,我将 firstOrNew() 更改为 firstOrCreate() 所以我不必手动保存成分。
    猜你喜欢
    • 2019-10-16
    • 2017-06-21
    • 2018-03-16
    • 2015-06-06
    • 2013-05-15
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多