dimanche 25 février 2018

How to update record in pivot table in laravel

I have 3 tables which are

  1. Products
  2. Colors
  3. Sizes
  4. color_product_sizes

Products has many to many relation with color and size. In the table number 4 along with ids of other table there is an additional column name quantity. So when I am trying to update the quantity of a particular colored and sized product I am using the following block of code

protected function updateProductStock($product,$items){
        foreach ($items as $color){
            foreach ($color->sizes as $size){
                $new = Sizes::with(['product' => function($query) use($product){
                    return $query->where('id',$product->id)->first();
                }])->where('id',$size->id)->first();
                $prd = $new->product;
                $stock = $prd[0]->pivot->quantity;
                $new_stock = $stock - $size->quantity;
                $new->product()->updateExistingPivot($product,['color_id' => $color->id , 'quantity' => $new_stock]);
            }
        }

    }

But it seems that nothing is changing at all. What is the problem and how to solve?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire