本文介绍了Yii2 isnewrecord 产生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 yii2 设置中,我有多个模型 - 一个是一对多模型,在表单中我可以编辑字段集或添加新记录.

In yii2 set-up I have multiple models - one being one to many with repeat fields in form where I can edit fieldset or add new records.

但我面临重复密钥错误的问题.

but I am facing issue of duplicate key error.

为了克服同样的问题,我正在尝试使用以下代码:

To overcome the same I am trying this code:

try{
     $userchild->save();
    }
    catch(\Exception $e){
    $userchild->isNewRecord = false;
    $usrchild->save();
}

但我得到了例外:

Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\controllers\UserController::setIsNewRecord()

我在这里缺少什么?

更新更多代码:

if ($model->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && $billinginfo->load(Yii::$app->request->post()) ) {

    $model->username = $model->email;
    $model->save();
    $profile->save();
    $billinginfo->save();
    if (!empty($_POST['UserChildren']) && !is_null($_POST['UserChildren'])) {
     foreach($_POST['UserChildren'] as $rows){

           $userchild = New UserChildren;                            
           $userchild->user_id = $model->id; 
           $userchild->id =$rows['id'];
           $userchild->attributes=$rows;  
           try{
                $userchild->save();
              } catch(\Exception $e){                            
                $userchild->setIsNewRecord(false);
           $usrchild->save();
            }
       }

  }        

现在我收到错误:

Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: app\models\UserChildren::_attributes     

推荐答案

如果你想分配你应该使用的属性

if you want assigng the attributes you should use

 $userchild->setAttributes($rows, TRUE);

https://www.yiiframework.com/doc/api/2.0/yii-base-model#$attributes-detail

https://www.yiiframework.com/doc/api/2.0/yii-base-model#$attributes-detail

这篇关于Yii2 isnewrecord 产生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 19:09