gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:53:45 25 4
gpt4 key购买 nike

想要使用 laravel 更新数据。我在模型中创建了一个函数,并在 Controller 中使用了该方法,但是在调用该方法时,它使用新的 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();}

最佳答案

您可以这样做:

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。数组。

关于php - Laravel save() - 插入数据而不是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40589005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com