get summary of related model via STAT relation

STAT relation tips ΒΆ

typical scenario: invoice, invoice items.

goal: amount summary from invoice items.

I was looking for a better solution for this scenario, even attempted to creat a 'new' relation call 'SUM', however I did not like any of approaches I was trying to take.

finally ... tata ... :

in your Invoice model :

public function relations()
	return array(
		'items'=>array(self::HAS_MANY,  'Invoiceitem', 'invoice_id'),
		'itemsTotal'=>array(self::STAT,  'Invoiceitem', 'invoice_id', 'select' => 'SUM(amount)'),
		'itemsCount'=>array(self::STAT, 'Invoiceitem', 'invoice_id'),

in your admin view :

<?php $this->widget('zii.widgets.grid.CGridView', array(
           'header'=>'Invoice Total',
)); ?>

more in your model:

'itemsMax'=>array(self::STAT,  'Invoiceitem', 'invoice_id', 'select' => 'Max(amount)'),
'itemsAVG'=>array(self::STAT,  'Invoiceitem', 'invoice_id', 'select' => 'AVG(amount)'),
4 1
Viewed: 25 053 times
Version: 1.1
Category: How-tos
Written by: rootbear
Last updated by: YiiJeka
Created on: Sep 15, 2013
Last updated: 7 years ago
Update Article


View all history