Total from Generated Column?
2 posts by 2 authors in: Forums > CMS Builder
Last Post: April 18, 2024 (RSS)
By mark99 - April 18, 2024
I'm just wondering if I can use the new Generated Column fields to perform a simple totally task.
Essentially, I'm using a multi-record editor and one of my textfields in each record (simply called 'cost') is for the cost of a product, where I put a normal numerical value like 10 or 6.3 etc. But can I use the new Generated Columns field to essentially create a total for all my 'cost' field records? I'm not quite sure how to approach this in CMSB.
By Dave - April 18, 2024
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.
interactivetools.com