简单的afterSave方法在Yii中不起作用

Moe*_*ini 3 php mysql activerecord yii

我想通过afterSave方法更新插入raw中的字段,因此我在Driver Model中开发了以下代码

protected function afterSave() {
        parent::afterSave();
        if ($this->isNewRecord) {
            $newid = self::newid($this->id);
            $this->updateByPk($this->id, new CDbCriteria(array('condition'=>'driverid = :driverid', 'params'=>array('driverid'=>  $newid))));
        }
}
Run Code Online (Sandbox Code Playgroud)

以及在控制器中使用的方法:

public function actionCreate()
{
    $model=new Driver;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Driver']))
    {
        $model->attributes=$_POST['Driver'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}
Run Code Online (Sandbox Code Playgroud)

为什么保存后不起作用?

编辑:

    private static function CheckNumber($number) {
        $array = array(10);
        for ($i = 0; $i < 10; $i++)
            $array[$i] = 0;
        do {
            $array[$number % 10]++;
            $number /= 10;
        } while ((int) ($number / 10 ) != 0);
        $array[$number]++;

        for ($i = 0; $i < 10; $i++)
            if ($array[$i] > 1)
                return false;
        return true;
    }

public static function newid($id) {
    while (self::CheckNumber($id) == FALSE) {
        $id++;
    }
    return $id;
}
Run Code Online (Sandbox Code Playgroud)

Raj*_*hal 5

你的updateByPk搞砸了......

检查文档

因为它不清楚你想要做什么..所以我假设你想通过self::newid($this->id);刚插入的行的结果更新driver_id值..

你应该做的是:

protected function afterSave() {
    parent::afterSave();
    if ($this->isNewRecord) {
        $newid = self::newid($this->id);
        $this->driverid = $new_id;
        $this->isNewRecord = false;
        $this->saveAttributes(array('driverid'));
    }
}
Run Code Online (Sandbox Code Playgroud)

是的,你的使用是正确的 afterSave()

isNewRecord即使在创建新记录后也是如此,但在第一次之后,它将始终为false.

来自Yii论坛由羌自己说..