如何在yii中更新时如何在数据库中插入新行?

时间:2014-09-16 05:13:42

标签: php yii

这是我的代码

是的,大家能帮帮我吗?我希望我的系统在yii框架中更新它时插入新记录

public function actionUpdate($id)<br/>
{
    $model=$this->loadModel($id);

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

    if(isset($_POST['Entrydata']))
    {
        $_POST['Entrydata']['photo'] = $model->photo;
        $model->attributes=$_POST['Entrydata'];
        $uploadedFile = CUploadedFile::getInstance($model,'photo');

        if($model->save())
        {

            if(!empty($uploadedFile))  // check if uploaded file is set or not
            {
             $uploadedFile->saveAs(Yii::app()->basePath.'/../images/'.$model->photo); // image will uplode to rootDirectory/banner/
            }  
            $this->redirect(array('view','id'=>$model->id_entry)); 
        }


    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

1 个答案:

答案 0 :(得分:0)

保存前取消设置属性。

 $model->unsetAttributes(array("id_entry"));

public function actionUpdate($id)
{ 
    $model=$this->loadModel($id);

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

    if(isset($_POST['Entrydata']))
    {
        $_POST['Entrydata']['photo'] = $model->photo;
        $model->attributes=$_POST['Entrydata'];
        $uploadedFile = CUploadedFile::getInstance($model,'photo');

         // Unset Primary Key value.
         $model->unsetAttributes(array("id_entry"));

        if($model->save())
        {

            if(!empty($uploadedFile))  // check if uploaded file is set or not
            {
             $uploadedFile->saveAs(Yii::app()->basePath.'/../images/'.$model->photo); // image will uplode to rootDirectory/banner/
            }  
            $this->redirect(array('view','id'=>$model->id_entry)); 
        }


    }

    $this->render('create',array(
        'model'=>$model,
    ));
}