在Yii框架中替换来自相同id用户的数据

lmyy7pcs  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(145)

如何修复此错误?我无法从与my _from相同的ID中替换数据:

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Update'); ?>
</div>

这是我的控制器操作Create:

public function actionCreate()
{
    $model=new TblUasUts;

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

    if(isset($_POST['TblUasUts']))
    {
        $model->attributes=$_POST['TblUasUts'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->nim_mhs));
    }

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

这是我得到的错误:
CDb命令用于创建语句SQL:数据库状态[23000]:完整性约束冲突:1062关键字“PRIMARY”的条目“2010140360”重复

o2gm4chl

o2gm4chl1#

这是因为你试图用现有的主键id保存元素。如果你想更新数据库中的现有条目,你应该从数据库中加载ActiveRecord(TblUasUts::model()-〉findByPk)。你也可以从$_POST数组中取消设置字段id,并每次在数据库中创建新行。

public function actionCreate()
{
$model=new TblUasUts;

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

if(isset($_POST['TblUasUts']))
{
    if (isset($_POST['TblUasUts']['id']) && $_POST['TblUasUts']['id']) {
        $model = TblUasUts::model()->findByPk((int)$_POST['TblUasUts']['id']);
    }

    $model->attributes=$_POST['TblUasUts'];
    if($model->update())
        $this->redirect(array('view','id'=>$model->nim_mhs));
}

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

}

n3h0vuf2

n3h0vuf22#

删除并保存更新:

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Update'); ?>
</div>

and this is my Controller action Create :

public function actionCreate()
{
    $model=new TblUasUts;

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

    if(isset($_POST['TblUasUts']))
    {
        $model->attributes=$_POST['TblUasUts'];
        if($model->update())
            $this->redirect(array('view','id'=>$model->nim_mhs));
    }

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

同时检查您是否使您的ID字段自动递增和主要以及。

相关问题