0

I collected data from a database and the data is based upon user id, ie I select data from database table based on a user id. Now the selected result has some value (numbers); how do I check if that total sum of the number is equal to a certain amount?

Using Laravel 5.4, I query my db as follows:

 $money = $DBTable::where('id', Auth::user()->id)->get();

Now I have a column called cash how do I get the total sum of the cash column? What is the code for that since the result is an object I do a foreach loop

 foreach ($money as $key => $value) {
     count($money->cash);
 }

this will return the number count of the value:

 foreach ($money as $key => $value) {
     echo $earn->earned_amount + $earn->earned_amount;  
 }

This will add up individual values to themselves, so please can anyone tell me how this is done?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dagogodboss
  • 483
  • 1
  • 4
  • 19

1 Answers1

0

There are two ways to do this:

  1. The Query builder way (https://laravel.com/docs/5.4/queries#aggregates)

    DB::table('table name')->where('user_id', Auth::user()->id) ->sum('cash');

  2. The eloquent way (https://laravel.com/docs/5.4/collections#method-sum)

    Auth::user()->cashTransactions->pluck('cash')->sum('price');

I assumed you table $DBTable has a model attached to it and that you have a relationship defined between the table's model and the user model

To define relationship you do:

in User model:

public function cashTransactions()
{
     return $this->hasMany('App\CashTransactions');
}

in CashTransactions model:

public function user()
    {
         return $this->belongsTo('App\User');
    }

Edit: you can also define relationships in a model with the same model (self relationship)

Indra
  • 692
  • 6
  • 18