Total from Generated Column?

2 posts by 2 authors in: Forums > CMS Builder
Last Post: April 18   (RSS)

By Dave - April 18

Hi Mark, 

Generated columns is more for when you want to sum up multiple fields within a single row.  Say you had cost and tax and wanted to show them together.

What's it for?  If you want to get a sum of all the fields in a table from all the rows you could do something like this with ZenDB:  

$table   = "products";
$field   = "cost";
$results = DB::query("SELECT SUM($field) FROM :_$table")->orThrow();
$sum     = $results->row(0)->col(0)->raw();
showme($sum);

// or all in one line
$sum = DB::query("SELECT SUM(cost) FROM :_products")->orThrow()->row(0)->col(0)->raw();

Here's what the different parts do: 

  • DB::query - executes a MySQL query and returns the result
  • SELECT SUM(cost) FROM :_products - the MySQL query, ":_" gets replaced with the table prefix
  • ->orThrow() - outputs (throws) an error if there is an error with the sql
  • ->row(0) gets the first row of the result
  • ->col(0) gets the first column
  • ->raw() returns the actual value (not an object)

Also, you might want to get your cost column type to DECIMAL in the field editor so you are guaranteed numeric values.

Let me know if that works for you.

Dave Edis - Senior Developer
interactivetools.com