Home  >  Q&A  >  body text

Update numeric data in two rows using Laravel MySQL

I have a details table in my database that contains the number of rows.

See below. Divided into two rows, one column contains Rs 1250, 1250. I showed a total of 2500. But when the user wants to use the full total I want to update the data in two columns, how to update these two rows in laravel?

$wallet_details = tbl_wallet_detail::where('wd_parent_id', $usewallet->wm_id)
    ->whereMonth('tbl_wallet_details.wd_start_date', date('m'))
    ->whereYear('tbl_wallet_details.wd_start_date', date('Y'))->first();

$wallet_details->wd_used_amount = $wallet_details->wd_used_amount + $request->usewallet;
$wallet_details->wd_remaining_amount = $wallet_details->wd_remaining_amount - $request->usewallet;
$wallet_details->save();

P粉161939752P粉161939752244 days ago288

reply all(1)I'll reply

  • P粉642436282

    P粉6424362822024-02-18 09:34:07

    I don't know all the details of your use case (e.g. how do you get the amount user has used), however, one way to solve your problem is outlined below. < /p>

    I created a Wallet model and associated table for this example and defined a used column on it to represent the amount used, and similar remaining< /代码> columns. Obviously, you can replace these with your specific information.

    $wallet = \App\Models\Wallet::where('user_id', 1)
        ->selectRaw('sum(used) as total')
        ->groupBy('used')
        ->first();
    
    $remaining = $wallet->total - 1500;
    
    \App\Models\Wallet::where('user_id', 1)
        ->update([
            'remaining' => $remaining / $wallet->count()
        ]);
    1. First, we run the query to sum (total) the used field values ​​for a given user
    2. Next we calculate the $remaining amount by subtracting the amount used (in your example 1500) from the total amount obtained in step 1
    3. Finally, we update the
    4. remaining columns for each row in the table for a given user
    As mentioned above it's up to you how to get the relevant rows from the table, using

    user_id is just an example but you can use transaction id or whatever makes sense for your use case .

    reply
    0
  • Cancelreply