Laravel如何在列的每一行中保存新值?

问题描述

我有一张桌子,请参见下面的migration

Schema::create('products',function (Blueprint $table) {
        $table->id();
        $table->integer('group');
        $table->string('code');
        $table->string('name');
        $table->double('price');
        $table->timestamps();
    });

我想将每行column = price的值增加一个我从input form收到的值。我能够看到可以获取并提高的价格,但是我在努力寻找如何在增加价值时保存它们。

我尝试过的事情:

public function increase(Request $request){

    $products = DB::table('products')->select('price')->get();
    $percentage = $request['increase'];

    foreach ($products as $product) {
       $price = $product->price * ((100 + $percentage)/100);
       $product->price = $price;
       $product->save();
    }

}

但是我遇到了错误Call to undefined method stdClass::save()

解决方法

您可以在一条语句中完成该操作:

 $percentage = $request['increase'];

   DB::table('products')->update(['price'=> DB::raw("price * ((100 + {$percentage})/100)")]);