在laravel中使用update或Create进行增量

Nis*_*ung 3 laravel eloquent illuminate-container laravel-5.1

我想做的是更新或插入表中的行。就我而言,更新看起来像这样:

\DB::table('inventories')->where('product_code',$product_code)->increment('stock_current_quantity',$quantity);
Run Code Online (Sandbox Code Playgroud)

我不想使用if else语句。我真正想要的是将增量集成到以下语句中,以便按上述语句进行更新。

 \App\Inventory::updateOrCreate(['product_code' => $product_code], ['stock_current_quantity'=>$quantity]);
Run Code Online (Sandbox Code Playgroud)

提前致谢!

小智 18

因为 google 把我带到了这里,我认为这里的答案,尤其是当你只想使用 updateOrCreate 时,并不像这样令人满意:

\App\Inventory::updateOrCreate([
         'product_code' => $product_code
    ], 
    [
         'stock_current_quantity' => \DB::raw('stock_current_quantity + 1')
    ]
);

Run Code Online (Sandbox Code Playgroud)

归功于这个人

  • 它在创建时不起作用(实际上是“INSERT”),因为字段“stock_current_quantity”尚未设置。 (2认同)

Ini*_*igo 12

我正在使用 Laravel 7.8.1 并将其全部合并到一个语句中,如下所示工作正常:

    $user->league_entries()->updateOrCreate([
        'month' => $month,
        'year' => $year
    ])->increment('score');
Run Code Online (Sandbox Code Playgroud)


San*_*ruz 6

为什么不这样做:

$inventory = \App\Inventory::firstOrNew(['product_code' => $product_code]);

$inventory->stock_current_quantity = ($inventory->stock_current_quantity + $quantity);
$inventory->save();
Run Code Online (Sandbox Code Playgroud)

如果模型不存在,$inventory->stock_current_quantity将仅等于$quantity,否则将以递增$quantity