mardi 16 juillet 2019

How to update a total sum from a row based on id in php mysql

I have the following columns in my database using MySQL.

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

However, let's say that I want to update one specific row in a form i.e. product_2 by 1.

id|product_1|product_2|product_3|Total
1    25         26        25       76

How do I accomplish the above using either Raw or Eloquent MySQL?

I've tried so many things like changing my code, searching on Google, YouTube, but I couldn't find a solution.

So the code below is what loads my table with populated data from MySQL.

public function index()
{
    $ProductsPost = ProductsPost::all();

    return view('products/index')->with(
        [
            'products_post' => $ProductsPost 
        ]
    );
}

Below is my update function.

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.']);
    }
}

Am I supposed to add an update here to the total column?

Again, the result I'm looking for is the total sum of columns in a row based on id. For example, if product_2 changes to a different value, I want that reflected for the Total column. The Total column should sum the collection of values from the three columns product_1, product_2, product_3.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire