多行求和和更新

Multiple row sum and update

我想更新多行,而所有这些行都将与他们以前的记录相加。例如,在名为“products”的 table 中有 2 个产品“a”和“b”,它们有一个名为“quantity”的列。假设产品“a”的数量为 20,产品“b”的数量为 25。现在我插入两个产品的新数量(产品“a”的新数量为 5,产品“b”的新数量为 4 ).查询应该在插入之前更新两个产品的数量,比如产品“a”的数量为 25,产品“b”的数量为 29。我的代码是:

foreach ($request->product_id as $key => $value) {
    $input['quantity'] = $request->product_quantity[$key];
    $update_stock = Product::update(['id'=>$request->product_id[$key]], 
    $input);
}

你可以在这里使用increment

假设请求数组是,

$productsWithQty = [
    1 => 5,
    2 => 4
];

其中 1 和 2 是您的产品 ID,分别是产品 A 和 B,5 和 4 是数量。所以查询将是,

foreach ($productsWithQty as $product => $qty) {
    Product::findOrFail($product)->increment('quantity', $qty);
}

试试这个,让我知道结果。