Updating a single row of pivot table There is a pivot table, order_item with additional attribute of size and quantity.
I've two record in the pivot table where both have different attribute and quantity.
$shirtExists = $order->shirts()->where('id', $shirtId)->where('size', $size)->first();
But when I ran
$shirtExists->pivot->update(['quantity' => $newQuantity]);
It updates both record's quantity.
How to fix this?
Updating A Record On A Pivot Table
If you need to update an existing row in your pivot table, you may use updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:
$user = App\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);
From the documentation ..
I want the sql perform like this.
UPDATE `order_shirt` SET `quantity` = '4' WHERE `order_shirt`.`order_id` = 1 AND `order_shirt`.`product_id` = 1 AND `order_product`.`size` = 's';
whenever i used updateExistingPivot it will update other shirt's quantity record with the same id but different size.
I solved the problem by using the DB facade.
public function updateOrderedQuantity($quantity, $orderId, $productId, $attribute)
{
$query = DB::table('order_product')
->where('order_id', $orderId)
->where('product_id', $productId)
->where('attribute', $attribute)
->update(['quantity' => $quantity]);
}
Please sign in or create an account to participate in this conversation.