本文介紹了laravel 的 updateOrCreate 方法的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我的方法中有以下代碼,我通過(guò)ajax發(fā)送到控制器方法:
I have the following code in my method which I am sending via ajax to the controller method :
$newUser = AppUserInfo::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();
});
現(xiàn)在的問(wèn)題是我的表中有一條記錄,但上面的代碼創(chuàng)建了另一個(gè)記錄,第二個(gè)是它在每次單擊按鈕(請(qǐng)求)時(shí)創(chuàng)建乘以兩條記錄.
推薦答案
在您的用例中,您應(yīng)該指定第二個(gè)參數(shù).第一個(gè)表示匹配的條件,第二個(gè)用于指定要更新的字段.
In your use case, you should specify a second parameter. The first indicates the conditions for a match and second is used to specify which fields to update.
$newUser = AppUserInfo::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 = AppFlight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
這篇關(guān)于laravel 的 updateOrCreate 方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!