Laravel updateOrCreate方法

70

我在我的方法中有以下的代码,我通过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();
});

现在的问题是我的表格里已经有一条记录,但以上的代码会创建另一条记录,并且每次按钮点击(请求)都会导致记录翻倍。

3个回答

164

在您的使用情况下,应该指定第二个参数。第一个参数表示匹配条件,第二个参数用于指定要更新哪些字段。

$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#other-creation-methods

// 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]
);

7
如果我说错了,请阻止我,但是看这种方法的工作原理,我不认为第二个参数中的 'user_id' => Auth::user()->id, 是必要的。Builder::updatedOrCreate() 将第一个参数发送到 firstOrNew(),这意味着如果需要创建新条目,您的用户ID将自动应用于该条目。 - kmuenkel
1
很好的发现@Claymore!我已经更新了我的代码片段。它可以正常工作,但这样做肯定更好。 - Rhu
你如何选择数据库中应该检查哪个表? - TheCrazyProfessor
这对我有帮助。我们的代码中有一个Fylke::updateOrCreate($county)的语句,其中$county是一个数组,第一个元素为键。我将代码更改为 $key = array_slice($county, 0, 1); Fylke::updateOrCreate($key, $county);问题解决了。谢谢。 - Erlend
1
永远不会过时,如果我有疑惑,我总是来这里。 :D - Vipertecpro
显示剩余3条评论

12

Eloquent 有一个叫做 updateOrCreate 的方法,可以像下面的例子一样使用:

<?
$flight = 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')
    ],
);
  1. 通过user_id进行搜索可能是识别行的最佳方式。
  2. 它根据第二个数组中给定的值创建或更新。

以下是该方法的标志。

/**
 * Create or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model
 */
public function updateOrCreate(array $attributes, array $values = [])

如何添加一个可有可无的搜索列呢?我的意思是,这个字段既可以有值也可以为空。我在 这个答案 中所解释的数组中找不到实现它的方法。 - Pathros
你如何更新 belongsTo 关联列? - Pathros

0
在Laravel中,createOrUpdate()方法用于确定数据是否存在,然后在表中创建新条目或更新现有条目。
注意:在您的情况下,应在该方法中包含一个条件。否则,它将创建一个新条目。
例如,如果您希望检查user_id,代码如下所示:
$newUser = \App\UserInfo::updateOrCreate([
    //Add your condition here.
    //For ex: you want to add or update data by user_id:
    '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')
]);

使用这两个参数,该方法将检查指定的授权用户ID是否存在,然后更新数据;否则,它将创建新的数据。
请查看官方文档: https://laravel-news.com/firstornew-firstorcreate-firstor-updateorcreate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接