Laravel 拉雷维尔。如何在列的每一行中保存新值?
我有一张表,请参见下面的Laravel 拉雷维尔。如何在列的每一行中保存新值?,laravel,query-builder,Laravel,Query Builder,我有一张表,请参见下面的迁移: Schema::create('products', function (Blueprint $table) { $table->id(); $table->integer('group'); $table->string('code'); $table->string('name'); $table->double('price'); $
迁移
:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->integer('group');
$table->string('code');
$table->string('name');
$table->double('price');
$table->timestamps();
});
我想将每行的列=price
增加一个我从输入表单
收到的值。我能够看到我能够收回的价格,然后价格上涨,但我正在努力找出如何在价格上涨时保存每一个价值
我尝试的是:
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();
}
}
但是我得到一个错误,
调用未定义的方法stdClass::save()
您可以在一条语句中完成:
$percentage = $request['increase'];
DB::table('products')->update(['price'=> DB::raw("price * ((100 + {$percentage})/100)")]);
您需要首先找到要更新的数据。添加
$product=DB::table('products')->find($id)
到foreach并更改您的foreachforeach($products->id as$id)
您需要创建一个Product类的对象才能使用save方法?@AnkitJindal,谢谢,我确实有一个Product类,很抱歉没有将其添加到我的问题中。@xNoJustice,谢谢,我会尝试这个。