问题
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