2017-02-19 60 views
0

我正在使用Laravel 5.4。我做了兩個函數(插入和更新)。 當id沒有被發現時,它會碰到插入,否則會碰到更新方法。 一切正常,但更新緊要查詢不更新表。該方法對於angularjs http.post方法無法使用Elequent查詢更新Laravel 5.4中的表格

控制器功能:

public function postUserJson(Request $req) 
{ 
    //return "check". $req->input('id'); 

    if ($req->input('id')=='') { 
     $user = new User(); 
     $user->UserName = $req->input('username'); 
     $user->Password = $req->input('password'); 

     $user->save(); 
     return "inserted"; 
    } else { 
     $check= User::find($req->input('id')); 

     // $check->ID = $req->input('id'); 
     $check->UserName = $req->input('username'); 
     $check->Password = $req->input('password'); 

     $check->save(); 
     return "updated".$check; 
    } 
} 

這(return "updated".$check;)碼返回在控制檯:

updated{"ID":13,"UserName":"sadek","Password":"456"} 

enter image description here

上一頁的用戶名是薩德。編輯完成後,我在save()方法後用sadek編輯了名稱。但當我刷新它顯示sade

我如何更新表?

+0

沒有你的模型具有正確的可填寫字段? – Birdy

+0

'<?php namespace App; 使用Illuminate \ Database \ Eloquent \ Model; 類用戶延伸模型 { // }' – Fawel

+0

可填寫字段是在模型和示出爲陣列...實施例:保護$可填充= [「USER_ID」,「名稱」,「性別」,「電話','email']; – Birdy

回答

0

您正在json formate中發送數據。你的查詢字符串不一樣。見

"UserName" != username 

Password != password 

請確保這一點。

0

雄辯提供了處理所有你上面的邏輯的方法,它被稱爲updateOrCreate()

從文檔:

您也可能會遇到的情況要更新現有模型或者如果不存在,則創建一個新模型。 Laravel提供了一個updateOrCreate方法來一步完成此操作。像firstOrCreate方法,updateOrCreate仍然存在的模式,所以沒有必要調用save()

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'], 
    ['price' => 99] 
);