沃梦达 / 编程问答 / php问题 / 正文

laravel 的 updateOrCreate 方法

laravel updateOrCreate method(laravel 的 updateOrCreate 方法)

本文介绍了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 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:laravel 的 updateOrCreate 方法

基础教程推荐