Home » Php » php – Laravel Query Builder – sum() method issue

php – Laravel Query Builder – sum() method issue

Posted by: admin July 12, 2020 Leave a comment

Questions:

Ehi there, I’m new in laravel and I have some issues with laravel query builder.
The query I would like to build is this one:

SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id 
WHERE categories.kind == "1"

I tried building this but isn’t working and I can’t figure out where I am wrong.

$purchases = DB::table('transactions')->sum('transactions.amount')
    ->join('categories', 'transactions.category_id', '=', 'categories.id')
    ->where('categories.kind', '=', 1)
    ->select('transactions.amount')
    ->get();

I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here’s the db structure:

transactions(id, name, amount, category_id)

categories(id, name, kind)

How to&Answers:

You don’t need to use select() or get() when using the aggregate method as sum:

$purchases = DB::table('transactions')
    ->join('categories', 'transactions.category_id', '=', 'categories.id')
    ->where('categories.kind', '=', 1)
    ->sum('transactions.amount');

Read more: http://laravel.com/docs/5.0/queries#aggregates

Answer:

If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:

DB::table('table_name')
    ->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
    ->get();

Answer:

Aggregates methods of query builder are:

  1) max() 
  2) min()  
  3) sum()  
  4) avg()   
  5) count() 

You can use like,

 $purchases = DB::table('transactions')
     ->join('categories', 'transactions.category_id', '=', 'categories.id')
     ->where('categories.kind', '=', 1)
     ->sum('transactions.amount');