代码之家  ›  专栏  ›  技术社区  ›  Lars Mertens

Larvel要删除的多对多剩余id

  •  0
  • Lars Mertens  · 技术社区  · 7 年前

    雄辩的 在…上

    产品

    产品类别

    类别


    假设我在所有这些模型中都有一些记录。 产品类别的当前状态如下:

    id | category_id | product_id
    -----------------------------
    5  | 2           | 2
    6  | 3           | 3
    7  | 4           | 1
    

    现在,我将运行以下函数,以使用Eloquent更新我的记录:

    public function updateObject($request, $id){
        $model = Product_Category::find($id);
        foreach($request->except('_token', 'categories') as $key=>$value){
            $model->setAttribute($key, $value);
        }
        $model->save();
        $model->id;
    
        foreach($request->only('categories') as $key=>$value){
            foreach($value as $category) {
                $product_category = Product_Category::where(['category_id' => $category["id"], 'product_id' => $model->id])->first();
                if($product_category == null) {
                    $product_category = new Product_Category();
                    $product_category->category_id = $category["id"];
                    $product_category->product_id = $model->id;
                } else {
                    $product_category->category_id = $category["id"];
                    $product_category->product_id = $model->id;
                }
                $product_category->save();
            }
        }
    }
    

    如果满足以下条件,此功能将正常工作:

    • 您正在向表中添加新类别
    • 您正在为另一个值编辑现有类别

    如果出现以下情况,此功能将不起作用:

    • 您不是在添加或编辑,而是在从数组中删除类别

    我的问题 :当我编辑表Product_Category中的类别时,如果我的类别比以前少,但需要删除,我将保留以前列出的旧ID。


    我在执行函数之前已经考虑过删除,但不确定这是否是“雄辩的方式”

    3 回复  |  直到 7 年前
        1
  •  1
  •   lchachurski    7 年前

    雄辩的方法是按此处所述分离记录 https://laravel.com/docs/5.5/eloquent-relationships

    $user->roles()->detach($roleId);
    
        2
  •  0
  •   Raza Mehdi    7 年前

    从上述结构来看,类别与类别之间的关系似乎是多对多的;产品。

    适当的雄辩结构将是:

    类别模型

    public function products()
    {
        return $this->belongsToMany(Product::class)->using(Product_Category::class);
    }
    

    产品型号

    public function categories()
    {
        return $this->belongsToMany(Category::class)->using(Product_Category::class);
    }
    

    产品类别模型

    Product_Category

    use Illuminate\Database\Eloquent\Relations\Pivot;
    
    class Product_Category extends Pivot
    {
    //
    }
    
        3
  •  0
  •   Lars Mertens    7 年前

    我不得不使用拉腊维尔同步方法。

    foreach($request->only('categories') as $key=>$value) {
        $sync_data = [];
        for ($i = 0; $i < count($value); $i++) {
            $sync_data[$value[$i]["id"]] = ["product_id" => $model->id];
        }
        $model->categories()->sync($sync_data);
    }
    

    这将从Product_Category表中删除所有未使用的记录。并编辑相应的记录。