Question

I need the equivalent of

SELECT SUM(balance) as "total_balance" FROM users;

in Kohana3.

So, how to find a sum of the balance column of users table in Kohana3?

$total_balance = ORM::factory ( 'user' )->find ();//I want to change this string to find total_balance to be a sum of the balance column.
Was it helpful?

Solution

There is no SUM() equivalent in ORM. Kohana ORM doesn't provides much equivalents to native SQL functions.

As a workaround use DB::select() with DB::expr() like:

$total_balance = DB::select(array(DB::expr('SUM(`balance`)'), 'total_balance'))
    ->from('users')
    ->execute()
    ->get('total_balance');

Produced query:

SELECT SUM(`balance`) AS `total_balance` FROM `users`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top