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.
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)'),
Very neat - thanks for sharing
I'll try this out.
I have previously done something like this, but I think your solution is more elegant:
public function getTotalDuration($id) { $connection = Yii::app()->db; $command = $connection->createCommand('SELECT SUM(duration) FROM tbl_trainingsession_item where trainingsession_id = ' . $id); $minutes = $command->queryScalar(); $hours = floor($minutes / 60); $minutes = $minutes % 60; if ($hours > 0) { return sprintf("%d:%'02d", $hours, $minutes); } else { return $minutes . ' min'; } }
I'll be interested to see if there is any difference in performance.
thanks
thanks @trond, you could actually try out more as long as SQL allows. eg.
SUM(unit_price * qty)
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.