Query sum of database column using Active Record

You can use YII2 Active Record to query the sum of a database column.

Here is an example that gets total cost and total revenue for a given date range with status as CREDITED:

  1. $query = Ledger::find();
  2. $this->load($params);
  3.  
  4. $query->where(['status' => 'CREDITED']);
  5. $query->andWhere('date_created >= :begin_date',[':begin_date' => $this->begin_date]);
  6. $query->andWhere('date_created <= :end_date',[':end_date' => $this->end_date]);
  7. $cost = $query->sum('cost');
  8. $revenue = $query->sum('revenue');

Published by

Joel Bowers

Web developer since 1999. PHP, YII2, Laravel, Javascript, HTML, CSS, jQuery, Perl, Wordpress, MySQL.

One thought on “Query sum of database column using Active Record”

Leave a Reply

Your email address will not be published. Required fields are marked *