【问题标题】:How to update a total sum from a row based on id in php mysql如何根据php mysql中的id更新一行的总和
【发布时间】:2019-07-16 08:46:31
【问题描述】:

我在使用 MySQL 的数据库中有以下列。

 id|product_1|product_2|product_3|Total
 1    25         25        25       75

但是,假设我想更新表单中的一个特定行,即 product_2 by 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 更改为不同的值,我希望将其反映到 Total 列。 Total 列应将 product_1、product_2、product_3 三列的值集合相加。

【问题讨论】:

  • 理想情况下,您不会有 Total 列,需要时手动计算。但是,在您的情况下,是的,您也需要更新总数。相关:stackoverflow.com/questions/12838729/…
  • 任何时候你发现自己有枚举列(例如,2),警钟应该开始响起。考虑您的架构设计是否最优。

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

听起来像生成的列,您可以在迁移中使用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 作为列,看起来您需要进行一些规范化。

【讨论】:

    【解决方案2】:

    您应该在您的 product_1、product_2 和 product_3 列上添加一个“更新时”约束。在此列的每次更新中,总计将成为三个产品列的总和。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多