2015-10-17 75 views
1

我想要做的是更新或插入表中的行。在我的情况下,更新看起来像这样:update或创建laravel中的增量

\DB::table('inventories')->where('product_code',$product_code)->increment('stock_current_quantity',$quantity); 

我不想使用if语句。我真正想要的是将增量整合到以下语句中,以便更新为上述语句。

\App\Inventory::updateOrCreate(['product_code' => $product_code], ['stock_current_quantity'=>$quantity]); 

在此先感谢!

+0

为什么你不使用雄辩?雄辩模型非常简单。 –

回答

2

为什么不这样做:

$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增加它。

+0

非常感谢! :)我只是坚持updateOrCreate方法! –

+0

不客气! –

+0

数据库'stock_current_quantity'可能会在检索项目和保存项目之间发生变化。这就是为什么'increment'使用 – andrewtweber