Reputation: 511
How do I update a database column based on a value from a different column?
I have a query like the following which pulls current usage (example: 200):
$currentusage = CurrentPercentageModel::select('current_usage')->where('name', '=', 'User Name')->get();
I would like to update the same value +1 after the each time it passes certain conditions.
My save
query would look like this and adds a new row to the table with the new value (example: 201):
$currentusage = $currentusage + 1;
$savecurrentusage = new CurrentPercentageModel;
$savecurrentusage->current_usage = $currentusage;
$savecurrentusage->save();
How do I update the same value from the one I pull from my query?
Upvotes: 0
Views: 280
Reputation: 163808
If you just want to add 1 to one of the fields, I guess the simplest way will be using Query Builder's increment()
method:
DB::table('current_percentage')->increment('current_usage');
If you want to use Eloquent, you can do this:
$current = CurrentPercentageModel::where('name', '=', 'User Name')->first();
$current->update(['current_usage' => ++$current->current_usage]);
Upvotes: 1
Reputation: 4795
A bit messy but should works
$model = CurrentPercentageModel::where('name', '=', 'User Name')->first();
$model->current_usage += 1;
$model->save();
Upvotes: 1
Reputation: 563
Try this
$currentPercent = CurrentPercentageModel::where('name', '=', 'User Name')->first();
$currentusage = $currentPercent->currentusage + 1;
$currentPercent->current_usage = $currentusage;
$currentPercent->save();
Upvotes: 0