aftersave的方法求解..




//控制器中的方法

if(isset($_POST['Category']))

		{

			$model->attributes=$_POST['Category'];

			if($model->save())

            {

                

                $this->redirect(array('view','id'=>$model->id));

            }


		}

//model文件

public function aftersave()

    {

        parent::afterSave();

        $this->parentid = (int)substr($this->path,strripos($this->path,',')+1);

        $this->path .= ','.$this->id;

        self::save();

    }



执行update显示执行insert.:

CDbCommand 无法执行 SQL 语句: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘121’ for key ‘PRIMARY’. The SQL statement executed was: INSERT INTO category (parentid, name, path, id) VALUES (:yp0, :yp1, :yp2, :yp3)

不使用aftersave




//控制器

$model->attributes=$_POST['Category'];

			if($model->save())

            {

                $model->parentid = (int)substr($model->path,strripos($model->path,',')+1);

                $model->path .= $model->id.',';

                $model->save();

                $this->redirect(array('view','id'=>$model->id));

            }



成功执行了update操作

afterSave 本就是在save方法之后执行的 你已经save过了 已经保存在数据库了

然后你还在其中又做了: self::save(); 此时scenario还是insert所以你调用save方法还是做的insert操作

一种方法时切换掉scenario 并做判断 不然就是递归死循环

这样几乎导致递归了 :lol:

save() =========> afterSave() ===> save() =====>…

其实我都怀疑 self::save 是什么东西 静态类方法save()? 你即便用$this->save() 也可能导致递归的

你可能是想先保存再修改其中的字段 那么就用你现在用的方法 :D

看看insert方法 它是在最后才置场景为update的


 $this->_pk=$this->getPrimaryKey(); 

            $this->afterSave(); 

            $this->setIsNewRecord(false); 

            $this->setScenario('update'); 

            return true; 

明白了,谢谢