mercredi 25 octobre 2017

Laravel Many To Many leftover id's to delete

Currently I'm having 3 models in Eloquent on Laravel 5.5

Product

Product_Category

Category


Let's say I have some records in all of these models. Current state of Product_Category will be like this:

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

Now I will run the following function to update my records with 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();
        }
    }
}

This function will work fine if:

  • You're adding new categories to the table
  • You're editing existing categories for another value

This function will not work if:

  • You're either not adding or editing but removing a category from the array

My Question: How can I resolve this issue? So that the table Product_Category will always update with only the latest id's from the array

I've already thought about a delete before executing the function but not sure if this is the "Eloquent way"



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zDPg0D
via IFTTT

Aucun commentaire:

Enregistrer un commentaire