如何在Yii中使用afterSave()保存连续​​的平均值然后保存它

时间:2013-11-19 01:47:53

标签: php yii

  1. 在表格中,我有3列nota1,nota2,nota3表格Notas。
  2. 我想计算nota1,nota2,nota3
  3. 的平均值
  4. 然后我想使用beforeSave()方法保存nota_final字段
  5. 的平均结果

    这是我在模型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>
    

1 个答案:

答案 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
}