laravel updateOrCreate方法
我在我的方法中有以下代码,我通过ajax发送到控制器方法:
$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] );
我的代码是
CityProductTemp::updateOrCreate( [ 'city_id' => $city_id, 'product_id' => $product->product_id ], [ 'mrp' => $mrp, 'sale_price' => $sale_price, 'in_offer' => $in_offer, 'is_featured' => $is_featured, 'sort_number' => $sort_number ] );
where
子句中的未知列id
SQL: UPDATE city_product_temp SET mrp = 66, is_featured = 1, updated_at = 2017-09-15 15:23:17, in_offer = 0 WHERE `id` IS null