这是我在模型Notas.php中的代码:
public function getAvg()
{
$avg = Yii::app()->db->createCommand()
->select('(nota1 + nota2 + nota3)/3 as NotaFinal')
->from('notas')
->queryRow();
return $avg;
}
protected function afterSave()
{
if($this->isNewRecord){
$this->nota_final->Avg();
$this->isNewRecord= false;
$this->nota_final->saveAttributes($_POST['nota_final']);
if($model->save() == false) var_dump($model->errors);
}
return parent::afterSave();
}
它没有保存平均值,也没有显示任何错误。
怎么了?
我的观看/ notas / _form.php
tr>
<td><div class="row2">
<?php echo $form->labelEx($model,'nota1'); ?>
<?php echo $form->textField($model, 'nota1', array('maxlength'=>'3')); ?>
<?php echo $form->error($model,'nota1'); ?>
</div></td>
<td>
<div class="row2">
<?php echo $form->labelEx($model,'nota2'); ?>
<?php echo $form->textField($model,'nota2', array('maxlength'=>'3', 'input'=>'20px')); ?>
<?php echo $form->error($model,'nota2'); ?>
</div>
</td>
<td>
<div class="row2">
<?php echo $form->labelEx($model,'nota3'); ?>
<?php echo $form->textField($model,'nota3', array('maxlength'=>'3')); ?>
<?php echo $form->error($model,'nota3'); ?>
</div>
<td>
<div class="row2">
<?php echo $form->labelEx($model,'nota_final'); ?>
<?php echo $form->textField($model, 'nota_final', array('readOnly'=>true)); ?>
<?php echo $form->error($model,'nota_final'); ?>
</div>
答案 0 :(得分:0)
public function getAvg() // remove this method
{
}
protected function beforeSave() // change to beforeSave()
{
if($this->isNewRecord) {
// Copy attributes from $_POST
$this->nota_final->saveAttributes($_POST['nota_final']);
// Calculate average
$this->nota_final->avg =
($this->nota_final->nota1 + $this->nota_final->nota2 +
$this->nota_final->nota3) / 3;
// DO NOT NEED TO CALL ->save() here, it will result in loop.
// Do it in your controller, and this beforeSave method will be triggered
}
return parent::beforeSave(); // change to beforeSave
}