Revision #38 has been created by rackycz on Oct 5, 2020, 6:10:14 PM with the memo:
Child aggregation in Parent GridView
« previous (#37) next (#39) »
Changes
Title
unchanged
Yii v2 snippet guide II
Category
unchanged
Tutorials
Yii version
unchanged
2.0
Tags
unchanged
tutorial,beginner,yii2,snippets
Content
changed
[...]
**Displaying SUM of child models in a GridView with parent models**
---
... can be easily done by adding a MySQL VIEW into your DB, creating a model for it and using it in the "ParentSearch" model as the base class.
Let's show it on list of invoices and their items. Invoices are in table "invoice" (model Invoice) and their items in "invoice_item" (model InvoiceItem). Now we need to join them and sort and filter them by SUM of prices (amounts). To avoid calculations in PHP, DB can do it for us if we prepare a MySQL VIEW:
```sql
CREATE VIEW v_invoice AS
SELECT invoice.*,
SUM(invoice_item.units * invoice_item.price_per_unit) as amount,
COUNT(invoice_item.id_invoice) as items
FROM invoice[...]