我使用 MySQL 的数据库中有以下列。
id|product_1|product_2|product_3|Total
1 25 25 25 75
但是,假设我想将表单中的一个特定行(即 Product_2)更新 1。
id|product_1|product_2|product_3|Total
1 25 26 25 76
如何使用 Raw 或 Eloquent MySQL 完成上述任务?
我尝试了很多方法,例如更改代码、在 Google、YouTube 上搜索,但找不到解决方案。
下面的代码是用 MySQL 中填充的数据加载我的表的。
public function index()
{
$ProductsPost = ProductsPost::all();
$sum_total = ProductsPost::select(DB::raw('product_1 + product_2 + product_3 as total_products'))->where('id', 1)->total_products;
return view('products/index')->with(
[
'products_post' => $ProductsPost,
'sum_total' => $sum_total
]
);
}
下面是我的更新函数。
public function update(Request $request, $id)
{
$ProductsPost = ProductsPost::find($id);
$ProductsPost->update($request->all());
ProductsPost::where('id', $id)->sum('product_1', 'product_2', 'product_3');
if ($ProductsPost->wasChanged()) {
// changes have been made
return redirect('products')->with(['success' => 'Changes were successfully saved.']);
} else {
return redirect('products/'.$id.'/edit')->with(['error' => 'No changes made.']);
}
}
我应该在此处向总计列添加更新吗?
同样,我要查找的结果是基于 id 的一行中的列的总和。例如,如果 Product_2 更改为不同的值,我希望将其反射(reflect)到“总计”列中。总计列应对三列product_1、product_2、product_3 中的值集合进行求和。
最佳答案
听起来像是生成的列,您可以在迁移中使用storedAs($expression)
修饰符,如下所示:
Schema::create('products_posts', function (Blueprint $table) {
$table->double('product_1');
$table->double('product_2');
$table->double('product_3');
$table->double('total')->storedAs('product_1 + product_2 + product_3');
});
或
您可以使用virtualAS($expression)
修饰符,其值将动态计算,但根据您想要存储值并在插入或更新时更新的场景.
请参阅Documentation还有这个Question也是。
注意
product_1、product_2、product_3 作为列,看起来您需要进行一些标准化。
关于php - 如何根据php mysql中的id更新一行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053439/