Yii2 isnewrecord generates exception

怎甘沉沦 提交于 2019-12-24 23:03:56

问题


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();
}

but I am getting the exception:

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

What I am missing here?

update with more code:

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();
            }
       }

  }        

Now I am getting the error:

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

回答1:


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://stackoverflow.com/questions/49592758/yii2-isnewrecord-generates-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!