Search code examples
selectcountkohanakohana-3kohana-orm

Kohana3 ORM sum() equivalent


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.

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`