【发布时间】:2014-05-18 17:12:00
【问题描述】:
我正在使用 Yii 框架,但这可能与我的 php 代码有关。
我的控制器中有 3 个方法,1 个用于创建,1 个用于更新,1 个用于保存。 创建和更新呈现相同的表单。
保存记录一切正常。但是当我更新一条记录时,它会创建一条新记录。 在我的更新方法中,我加载了现有记录并获得了正确的值,但是当我保存它时,会将其保存在新记录中。我尝试使用 $model->update() 而不是 $model->save(),但我收到了无法更新新记录的错误。
提前感谢您的任何见解
方法创建
$model = new Comment;
$this->renderPartial('_formComment',array(
'model'=>$model,
'post_id'=>$post_id,)
);
方法更新
$model=$this->loadModel($comment_id);
$this->renderPartial('_formComment',array(
'model'=>$model,
'post_id'=>$model->post_id,
'comment_id'=>$model->id,)
);
保存方法
$comment=new Comment;
if(isset($_POST['Comment']))
{
$model->attributes=$_POST['Comment'];
if($model->save()) {
echo ('save ok');
}
}
我的更新方法调用的 loadmodel 函数
if($this->_model===null)
{
$this->_model=Comment::model()->findbyPk($comment_id);
if($this->_model===null)
throw new CHttpException(404,'The requested page does not exist.');
}
return $this->_model;
【问题讨论】:
-
有根据的猜测:您的表单为主键属性提交了一个空白值,而您的模型没有验证规则可以跳过它。
-
@DCoder 是的,你是对的。我以为只是做 $model->attributes=$_POST['Opinion'];将comment_id 设置为评论主键的当前值。但是当我将 $model->id 设置为当前评论 id 时,我得到了完整性错误,它尝试插入具有相同主键的记录。我尝试使用更新而不是保存,它仍然是一样的。正在尝试更新新记录。
-
您的“保存方法”看起来不正确,因为您正在混合使用
$comment和$model。您应该通过其 ID 加载现有评论,而不是new Comment。