lundi 4 novembre 2019

Duplicate key entry when updating object

I have a Product object that has multiple Shop objects because a shop can offer the same product at different prices / conditions.

I have an edit view for the products that lists the shops where the product is available.

When I make adjustments to the shops of the product eg. price; I get the error that the shop already exists in the database. I know the product exists, but I need the data to be updated.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 'PRIMARY'

    public function update(Request $request, $slug)
    {
        $product = Product::with('shops', 'type')->where('slug', $slug)->first();
       [... snip ...]

        $i = 0;
        foreach($product->shops as $shop) {
            $shop = request('shop');
            $product->shops()->attach($product->id, [
              'shop_id' => $shop[$i]['id'],
              'price' => $shop[$i]['price'],
              'url' => $shop[$i]['url']
            ]);
            $i++;
        }

        $product->save();

      return redirect('/'.$slug)->with('success', 'Product has been updated');
    }

$product->update(); yields the same result.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire