Tech Tip: ORDA query with related entities and aggregate function
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: November 29, 2022
ORDA query is a powerful tool that can perform queries more complex than basic "attribute = value" searches.
For example, given the following schema:
An order entity from dataclass "Orders" has many related entities from dataclass "Order_Items". The related entities can be obtained via the "Items" relation.
How to obtain all order entities that have "Total" equal to the sum of "Price" of their related entities?
In other words, how could an ORDA query be written that returns the same result as the routine below?
$orders_es:=ds.Orders.all() $orders_coll:=New collection For each ($orders_en; $orders_es) If ($orders_en.Total=$orders_en.Items.sum("Price")) $orders_coll.push($orders_en) End if End for each $result_es:=ds.Orders.fromCollection($orders_coll) |
One way is to use the eval() statement:
$result_es:=ds.Orders.query("eval(This.Total=This.Items.sum(\"Price\"))") |
Another way is to use Formula:
$result_es:=ds.Orders.query(Formula(This.Total=This.Items.sum("Price"))) |
Note that using Formula is recommended because it benefits from tokenization and easier readability.