gpt4 book ai didi

php - laravel updateOrCreate 方法

转载 作者:IT王子 更新时间:2023-10-29 00:00:45 30 4
gpt4 key购买 nike

我的方法中有以下代码,我通过 ajax 将其发送到 Controller 方法:

    $newUser = \App\UserInfo::updateOrCreate([
'user_id' => Auth::user()->id,
'about' => $request->get('about'),
'sec_email' => $request->get('sec_email'),
'gender' => $request->get("gender"),
'country' => $request->get('country'),
'dob' => $request->get('dob'),
'address' => $request->get('address'),
'mobile' => $request->get('cell_no')
]);

dd($request->all()) 给了我:

array:8 [
"_token" => "fHeEPfTvgMD3FpIBmmc6DmKXFaiuWKZEiOhg6twQ"
"about" => "Some about me."
"sec_email" => "example@gmail.com"
"country" => "Priority highest"
"gender" => "male"
"dob" => "12/12/1990"
"address" => "Some address"
"cell_no" => "234234234"
]

这是完美的。

jQuery 代码:

$('#submit-editProfile-form').on('click', function() {
var profileEditForm = $("#edit-user-profile");
var formData = $('#edit-user-profile').serialize();
profileEditForm.on('submit', function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:'/freelance/edit-userProfile-info',
type:'POST',
data:formData,
error: function (data) {
console.log('Error');
}
});
}).submit();
});

现在的问题是我的表中有一条记录,但是上面的代码创建了另一个,第二个是它在每次按钮单击(请求)时创建了两条记录。

最佳答案

在您的用例中,您应该指定第二个参数。第一个表示匹配的条件,第二个用于指定要更新的字段。

$newUser = \App\UserInfo::updateOrCreate([
//Add unique field combo to match here
//For example, perhaps you only want one entry per user:
'user_id' => Auth::user()->id,
],[
'about' => $request->get('about'),
'sec_email' => $request->get('sec_email'),
'gender' => $request->get("gender"),
'country' => $request->get('country'),
'dob' => $request->get('dob'),
'address' => $request->get('address'),
'mobile' => $request->get('cell_no')
]);

这是文档中的一个示例:https://laravel.com/docs/5.4/eloquent

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);

关于php - laravel updateOrCreate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42695943/

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