Yii v2 snippet guide II

Comparing #37 with #38

Revision #38 was created by rackycz rackycz on Oct 5, 2020, 6:10:14 PM.

Child aggregation in Parent GridView

Content

[...]
**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
[...]