PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 4, 2022

[FIXED] Laravel Query Builder - sum() method issue

 February 04, 2022     database, laravel, mysql, php, query-builder     No comments   

Issue

I'm new to laravel and I have some issues with the 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 it 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)


Solution

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



Answered By - Limon Monte
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing