本文介紹了laravel 的 updateOrCreate 方法的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我的方法中有以下代碼,我通過ajax發送到控制器方法:
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();
});
現在的問題是我的表中有一條記錄,但上面的代碼創建了另一個記錄,第二個是它在每次單擊按鈕(請求)時創建乘以兩條記錄.
推薦答案
在您的用例中,您應該指定第二個參數.第一個表示匹配的條件,第二個用于指定要更新的字段.
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]
);
這篇關于laravel 的 updateOrCreate 方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!