get summary of related model via STAT relation

You are viewing revision #1 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.

next (#2) »

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)'),
4 1
8 followers
Viewed: 27 209 times
Version: Unknown (update)
Category: How-tos
Written by: rootbear
Last updated by: YiiJeka
Created on: Sep 15, 2013
Last updated: 10 years ago
Update Article

Revisions

View all history