如何基于php MySQL中的id从行中更新总和

时间:2019-07-16 08:46:31

标签: 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更改为其他值,则希望该值反映在“总计”列中。 “总计”列应将三个列product_1,product_2,product_3中的值集合相加。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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