get summary of related model via STAT relation

4 1
8
Viewed: 30 352 times
Version: Unknown (update)
Category: How-tos
Written by: rootbear rootbear
Updated by: YiiJeka YiiJeka
Created: Sep 15, 2013
Updated: 12 years ago

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#1)next (#3) »

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(
	'id'=>'invoice-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		//~~~
		array(
           'header'=>'Invoice Total',
			'value'=>'$data->itemsTotal',
		),
		//~~~
	),
)); ?>

more in your model:

'itemsMax'=>array(self::STAT,  'Invoiceitem', 'invoice_id', 'select' => 'Max(amount)'),
'itemsAVG'=>array(self::STAT,  'Invoiceitem', 'invoice_id', 'select' => 'AVG(amount)'),