tekin erten tekin erten - 3 months ago 13
MySQL Question

update pivot table with multiple ids

$user = App\User::find(1);

$user->roles()->updateExistingPivot($roleId, $attributes);


this is what we use while update a pivot table . but I have two same values as
$roleId
in my table. I want to update only one of them. how can we do that?

For example; this is my sql table

userId -- roleId -- attributeId
1 1 1
1 1 2


this is another pivot table that explains better:

order_id --- product_id --- feature_id --- product_quantity


in an order I have multiple products.
Any products can have multiple features.
I am trying to save database the same product with different features in an order, and the problem begins here, it doesn't work with this commands:

$order = Order::create( $request->all());
$product_list = $request->input('product_list');
$feature_list = $request->input('feature_list');
$product_quantity = $request->input('product_quantity');

/* attach pivot table */
$order->product()->attach($product_list);

/* get the product list as array */
foreach($product_list as $key => $product_id)
{
$order->product()->updateExistingPivot($product_id, array(
'feature_id' => $feature_list[$key],
'product_quantity' => $product_quantity[$key], // product_quantity is array
));
}

Answer

I handled the problem by this way and it works... If you can find another solution, please share here... In my store function;

 public function store(OrderRequest $request)
    {
      $order = Order::create( $request->all());
      $product_row = $request->input('product_row'); 
      $product_list = $request->input('product_list');
      $feature_list = $request->input('feature_list');
      $product_quantity = $request->input('product_quantity');
      $product_status = $request->input('product_status' );

       /* attach pivot table */
       foreach($product_row as $key=>$value){

      $order->product()->attach($product_list[$key], ['feature_id'=>$feature_list[$key], 'product_quantity'=>$product_quantity[$key], 'product_status'=>$product_status[$key]] );

        }
}

and update function:

public function update(Order $order, OrderRequest $request) 
    {
      $order->update($request->all());

      $product_row = $request->input('product_row');
      $product_list = $request->input('product_list'); 
      $feature_list = $request->input('feature_list');
      $product_quantity = $request->input('product_quantity');
      $product_status = $request->input('product_status' );
      /* clear pivot table for the current order */
      $order->product()->detach();
      /* attach pivot table */
       foreach($product_row as $key=>$value){

      $order->product()->attach($product_list[$key], ['feature_id'=>$feature_list[$key], 'product_quantity'=>$product_quantity[$key], 'product_status'=>$product_status[$key]] );

        }
Comments