Laravel。如何在列的每一行中保存一个新值?
Laravel. How to save a new value in each row of a column?
我有一个table,请看下面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)")]);
我有一个table,请看下面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)")]);