updateOrCreate 增量 laravel
updateOrCreate with increment in laravel
我想做的是更新或插入 table 中的行。在我的例子中,更新看起来像这样:
\DB::table('inventories')->where('product_code',$product_code)->increment('stock_current_quantity',$quantity);
我不想使用 if else 语句。我真正想要的是将 increment 集成到以下语句中,以便它像上面的语句一样更新。
\App\Inventory::updateOrCreate(['product_code' => $product_code], ['stock_current_quantity'=>$quantity]);
提前致谢!
为什么不这样做:
$inventory = \App\Inventory::firstOrNew(['product_code' => $product_code]);
$inventory->stock_current_quantity = ($inventory->stock_current_quantity + $quantity);
$inventory->save();
如果模型不存在,$inventory->stock_current_quantity
只会等于$quantity
,否则,它将递增$quantity
。
如果其他人遇到此问题,只需贡献一下
它不存在,创建,但为零
self::firstOrNew(['product_code' => $product_code]);
然后,增加它...如果其他进程在我之前将它更新为 1(在 firstOrNew 和增量之间的中间时间),这将更新为 2,避免丢失之前的更新
self::where('product_code', $product_code)->increment('stock_current_quantity');
因为 google 把我带到这里,我认为这里的答案,尤其是当您只想使用 updateOrCreate 时,并不像这样令人满意:
\App\Inventory::updateOrCreate([
'product_code' => $product_code
],
[
'stock_current_quantity' => \DB::raw('stock_current_quantity + 1')
]
);
感谢this guy
我正在使用 Laravel 7.8.1 并将其全部合并到一个语句中,按照以下工作正常:
$user->league_entries()->updateOrCreate([
'month' => $month,
'year' => $year
])->increment('score');
我想做的是更新或插入 table 中的行。在我的例子中,更新看起来像这样:
\DB::table('inventories')->where('product_code',$product_code)->increment('stock_current_quantity',$quantity);
我不想使用 if else 语句。我真正想要的是将 increment 集成到以下语句中,以便它像上面的语句一样更新。
\App\Inventory::updateOrCreate(['product_code' => $product_code], ['stock_current_quantity'=>$quantity]);
提前致谢!
为什么不这样做:
$inventory = \App\Inventory::firstOrNew(['product_code' => $product_code]);
$inventory->stock_current_quantity = ($inventory->stock_current_quantity + $quantity);
$inventory->save();
如果模型不存在,$inventory->stock_current_quantity
只会等于$quantity
,否则,它将递增$quantity
。
如果其他人遇到此问题,只需贡献一下
它不存在,创建,但为零
self::firstOrNew(['product_code' => $product_code]);
然后,增加它...如果其他进程在我之前将它更新为 1(在 firstOrNew 和增量之间的中间时间),这将更新为 2,避免丢失之前的更新
self::where('product_code', $product_code)->increment('stock_current_quantity');
因为 google 把我带到这里,我认为这里的答案,尤其是当您只想使用 updateOrCreate 时,并不像这样令人满意:
\App\Inventory::updateOrCreate([
'product_code' => $product_code
],
[
'stock_current_quantity' => \DB::raw('stock_current_quantity + 1')
]
);
感谢this guy
我正在使用 Laravel 7.8.1 并将其全部合并到一个语句中,按照以下工作正常:
$user->league_entries()->updateOrCreate([
'month' => $month,
'year' => $year
])->increment('score');