2016-05-18 15 views
0

save()を使用してデータを挿入する際に問題があります。 save()を使用してデータを正常に更新します。しかし、データがperticular idのデータベースに存在しない場合、データは挿入されません。 コントローラ:save()を使用してデータが存在しない場合、データは挿入されません

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']); 

    } 

いずれの解決策も高度に適用されます。

+0

dadatが存在しない場合は、$ profile = $ this-> findModel1($ id)を置き換えます。 $ profile = new findModel1();を使ってください。 –

+0

更新と保存の両方に同じ操作を使用していますか?これについてもっと説明すれば$ idの使用は何か私はあなたを助けることができます。応答のために –

答えて

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

オブジェクトが見つからない場合。

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

thanx私はこれを試みたが、成功を収めていない。 – vikash

+0

ありがとうDanyal最終的に私の仕事です。 – vikash

0

この方法で確認できます。

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

これは、モデルがnullかどうかを確認してから新しいモデルオブジェクトを作成することです。保存を実行します。

関連する問題