2017-02-19 58 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] 
);