Laravel save() - 插入数据而不是更新

时间:2016-11-14 12:40:09

标签: php mysql laravel

想要使用laravel更新数据。我在模型中创建了一个函数,并在控制器中使用了该方法,但在调用方法时,它使用新的id.function插入数据,如下所示。

public function edit_client($req,$id) { 
    $client = new client(); 
    $client->find($id); 
    $client->name = $req->name; 
    $client->address = $req->address; 
    $client->email = $req->email; 
    $client->phone = $req->phone; 
    $client->gender = $req->gender; 
    $client->department = $req->department; 
    $client->update();}

2 个答案:

答案 0 :(得分:5)

您可以这样做:

public function edit_client($req,$id) { 
    $client = Client::find($id); 
    $client->name = $req->name; 
    $client->address = $req->address; 
    $client->email = $req->email; 
    $client->phone = $req->phone; 
    $client->gender = $req->gender; 
    $client->department = $req->department; 
    $client->save();
}

或使用update()方法:

public function edit_client($req,$id) { 
    $client = Client::where('id', $id)->update([
        'name' = $req->name,
        'address' = $req->address,
        'email' = $req->email,
        'phone' = $req->phone,
        'gender' = $req->gender,
        'department' = $req->department
    ]);
}

如果您决定使用update()方法,请不要忘记添加$fillable数组。

答案 1 :(得分:2)

试试这个例子:

    $obj= Client::where('id', $id)->update([
        'name' = $req->name,
        'address' = $req->address,
        'email' = $req->email,
        'phone' = $req->phone,
        'gender' = $req->gender,
        'department' = $req->department
    ]);