如果使用save()不存在数据,则不会插入数据


data is not inserted if not exist using save()

我遇到了使用save()插入数据的问题。使用save(),我成功地更新了数据。但当数据不存在于具有特定id的数据库中时,它不会插入数据。控制器:

public function actionContact()
  {
    //$profile=new Profile();
    $id=YII::$app->user->id;
    //$users=User::find()->where('id='.$id)->one();
    //$profiles=Profile::find()->where('user_id='.$id)->one();
    $this->layout="profile";
    $profile=$this->findModel1($id);
    $data=Yii::$app->request->post();
    if($data && $profile->validate()){
    $profile->mobile=Yii::$app->request->post('mobile');
    $profile->city=Yii::$app->request->post('city');
    $profile->zip=Yii::$app->request->post('zip');
    $profile->address=Yii::$app->request->post('zip');
    $profile->save();
    Yii::$app->session->setFlash("Contact-success", Yii::t("user", "Contact updated"));
    return $this->refresh();        
     }
    return $this->redirect(['/users/edit']);
  }

我们将高度重视任何解决方案。

$profile=$this->findModel1($id);

如果没有找到对象。

if(empty($profile)){
$profile = new Profile();
}

我认为您可以通过这种方式进行检查。

$profile=$this->findModel1($id);
if($profile == null)
{
   $profile = new Profile();
}

在这篇文章中,我检查了模型是否为null,然后创建新的模型对象。然后执行保存。