1

我的数据库中有两个表,用户和个人资料。Profile 有 user_id 作为主键。每个用户只能拥有一个配置文件。当我上传图像文件时,它的名称与该 user_id 一起存储在配置文件表中。当 profile 表中还有其他字段需要更新时,我首先检查是否已经存在具有该 user_id 的记录。在我的个人资料模型中,我写了

public function checkForSaveOrUpdate()
{
    return self::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
}

我的控制器文件看起来像这样

    public function actionCreateInfo()
      {
        $profile = new Profile;
        $profile->user_id = Yii::app()->user->id;

        if(isset($_POST['Profile']))
        {
            if($profile->checkForSaveOrUpdate() === null)
            {
                $profile->attributes = $_POST['Profile'];
                if($profile->save())
                    Yii::app()->user->setFlash('success','Profile has been saved successfully');
            }
            elseif($profile = $profile->checkForSaveOrUpdate())
            {
                $profile->attributes = $_POST['Profile'];
                if($profile->update())
                    Yii::app()->user->setFlash('success','Profile has been updated successfully');
            }

            $this->redirect(array('index'));
        }

        $this->render('createInfo',array('profile'=>$profile));
}

我的问题是当我已经在数据库中,在配置文件中有一条记录,并且我提交了一个新表单时,旧数据全部被删除,只有当前提交的值被更新,而它应该保留旧值并且只更新新值。

4

3 回答 3

1

如果您将模型设置为:

$model = new YourModel;

您将$model->isNewRecord设置为true

var_dump($model->isNewRecord); // true, in this case you use $model->save()

当您找到一条记录时,相同的属性将具有相反的值:

$model = YourModel::model()->findByPk(1);
var_dump($model->isNewRecord); // false - and now you use $model->update(), instead.
于 2013-03-02T10:01:06.737 回答
0

将您的功能更改为静态功能

 public static function checkForSaveOrUpdate()
    {
        return self::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
    }

然后将动作修改为

public function actionCreateInfo()
{
        $profile = Profile::checkForSaveOrUpdate();
        if($profile===null)
        {
            $profile=new Profile;
            $profile->user_id = Yii::app()->user->id;
        }
        if(isset($_POST['Profile']))
        {
            $profile->attributes = $_POST['Profile'];
            if($profile->save())
                Yii::app()->user->setFlash('success','Profile has been saved successfully');
           $this->redirect(array('index'));
        }

        $this->render('createInfo',array('profile'=>$profile));
}
于 2013-03-02T11:27:34.583 回答
0

您的POST数据可能包括所有模型属性,包括那些由用户设置为空字符串的留空;除非模型规则中另有说明,否则空字符串是大规模分配的可接受值;一个巨大的任务是你实际做的$profile->attributes = $_POST['Profile'];

一种解决方案是在控制器中取消设置您不想更新的那些属性,例如那些包含空字符串的属性。

但是这种规则应该在模型中定义并通过调用validate()方法来触发,你现在通过调用update(). 你最好打电话save(),因为内部电话validate()而不是update().

默认值的规则定义如下:

array(
    'attr_name',
    'default',
    'setOnEmpty' => true,
    'value' => null
)
于 2013-03-03T15:50:34.040 回答