使用模型对象更新yii中的数据

使用模型对象更新yii中的数据,yii,Yii,我是YII的新手 正在尝试使用以下代码更新用户的值 public function actionProfile(){ $model = new Users; if(isset($_POST['update'])){ $model->findByPk(Yii::app()->session['user_id']); $model->user_name = $_POST['Users'][

我是YII的新手 正在尝试使用以下代码更新用户的值

public function actionProfile(){

    $model = new Users;

    if(isset($_POST['update'])){            

            $model->findByPk(Yii::app()->session['user_id']);
            $model->user_name = $_POST['Users']['user_name'];
            $model->update();           
            $this->refresh();

            //echo '<pre>';
            //print_r($_POST);die;
        }
}

据我所知,当您需要更新模型数据时,只需加载现有模型,无需创建新模型。这就是为什么第二个模型适用于您

try{
     $model->update();
}catch (Exception $ex){
     die($ex->getMessage());
}

因为您没有将
用户id
分配给
$model
进行更新。试试下面的方法

由于您没有分配
用户id
(主键),因此它被视为新记录。因此,
更新
被中断。我还建议您添加如下错误报告

Users::model()->findByPk(Yii::app()->session['user_id']);// loading existing model

$model = new Users; //creating a new model instance
$model = $model->findByPk(Yii::app()->session['user_id']); //This line
$model->user_name = $_POST['Users']['user_name'];
$model->update();
try{
     $model->update();
}catch (Exception $ex){
     die($ex->getMessage());
}