Yii isNewRecord在之前是假的吗?

时间:2011-11-21 07:29:45

标签: php yii

我在我的模型中创建了一个beforeSave方法(扩展了GXActiveRecord),if isNewRecord永远不会被触发。我的beforeSave()被调用了。

当我打印$ this-> isNewRecord变量时,它是假的。 该变量何时设置为false? 我非常肯定它是新的

public function beforeSave(){


        if(parent::beforeSave())
            {
              if($this->isNewRecord){
                    $this->setAttribute('doc_status','new');
                    print "something";
              }else{
                  $this->setAttribute('doc_status','updated');
              }
            return  true;
            }  else { return false;

    }

3 个答案:

答案 0 :(得分:5)

如果您之前从未保存过,那么

CActiveRecord-> isNewRecord为false。

E.g。

$model = new Product;
$model->name = uniqid("bar");
echo "isNewRecord?".$model->isNewRecord; // 1 (true)
$model->save();
echo "isNewRecord?".$model->isNewRecord; // (false)

$model = Product::model();
$model->name = uniqid("foo");
echo "isNewRecord?".$model->isNewRecord; // (false)
$model->save();
echo "isNewRecord?".$model->isNewRecord; // (false)

答案 1 :(得分:5)

嗯,这可能为时已晚,无法回答,但我只是想把它弄出来,因为这已经造成了足够的混乱(至少对我而言)......

如果您在模型的beforeSave()中调用parent::beforeSave(),并在此之后测试isNewRecord,则它将始终评估为false,因为模型已保存。

您的模型建立在框架类之上,因此当您重写方法时,先执行任务,然后调用父方法。所以:

protected function beforeSave() {


if ($this->isNewRecord)
    //do something
else
    //do something else
/* some more code*/
parent::beforeSave();
return true;
}

您也可以像这样调用parent beforeSave():

return parent::beforeSave();

return true && parent::beforeSave();

希望这可以帮助其他通过谷歌找到这个问题的人。

答案 2 :(得分:2)

至少在我的情况下

print($this->isNewRecord);
print(parent::beforeSave());
print($this->isNewRecord);

在每一行中打印true

抱歉,我不知道如何回答上面的答案。