php - 如何根据php mysql中的id更新一行的总和

标签 php mysql laravel laravel-5 eloquent

我使用 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/

相关文章:

php - 在PHP中删除多维数组中特定键的重复值但删除最后一个?

php - MYSQL 触发器错误 phpmyadmin

mysql - 如何仅针对我输入的日期返回自连接查询的结果?

html - 如何使用 bootstrap 在 Laravel 6.0 中将按钮并排放置?我试过了,但还是一上一下

php - laravel Mysql 希腊字母显示怎么样?

laravel - 在 laravel AppServiceProvider 上获取错误

php - 如何防止 PreventDefault 从 $_POST 中删除提交按钮?

php - 如何使用准备好的语句在 PHP 中输​​出 MySQL 表

mysql - 我应该一直使用 CREATE VIEW 而不是 JOIN

mysql - 如何使用 MySQL 通过 LEFT JOIN 进行计数?