【问题标题】:In Laravel 5.8 how update only a few columns if row exists?在 Laravel 5.8 中,如果行存在,如何只更新几列?
【发布时间】:2020-01-04 06:53:43
【问题描述】:

我正在使用 updateOrInsert 在数据库中插入一行或更新它以防它已经存在。

从手册: https://laravel.com/docs/5.8/queries

更新或插入 有时您可能想要更新数据库中的现有记录,或者在不存在匹配记录时创建它。在这种情况下,可以使用 updateOrInsert 方法。 updateOrInsert 方法接受两个参数:一个用于查找记录的条件数组,以及一个包含要更新的列的列和值对数组。

updateOrInsert 方法将首先尝试使用第一个参数的列和值对来定位匹配的数据库记录。如果记录存在,它将使用第二个参数中的值进行更新。如果找不到记录,将插入一条新记录,其中包含两个参数的合并属性:

就我而言,我不想覆盖(更新)所有列,而只想覆盖 updated_at 列。

在 MySql 中,我使用 INSERT 和 ON DUPLICATE KEY UPDATE 指定唯一要更新的列。

如何在 Laravel 中使用 updateOrInsert 做到这一点?感谢您的任何建议。

DB::table('products')->updateOrInsert(
  ['upc' => $request->get('upc'),],
  ['upc' => $request->get('upc'),
    'name' => $request->get('name'),
    'created_at' => ...,
    'updated_at' => ...]
);

【问题讨论】:

    标签: laravel laravel-5.8


    【解决方案1】:

    如果你查看 Query Builder 的代码,你会发现 Laravel 也在执行两个查询:

    /**
    * Insert or update a record matching the attributes, and fill it with values.
    *
    * @param  array  $attributes
    * @param  array  $values
    * @return bool
    */
    public function updateOrInsert(array $attributes, array $values = [])
    {
        // See if record exists (query 1)
        if (! $this->where($attributes)->exists()) {
            // Do an insert (query 2)
            return $this->insert(array_merge($attributes, $values));
        }
    
        // Do an update (query 2)
        return (bool) $this->take(1)->update($values);
    }
    

    您可以复制此代码并更改:

    return (bool) $this->take(1)->update($values);

    return (bool) $this->take(1)->update(['updated_at' => '2019-08-31 12:34:45']);

    如果您确实想使用 INSERT with ON DUPLICATE KEY UPDATE,您应该使用 RAW 查询。 Laravel 查询构建器不支持仅 MySQL 的方法。

    原始查询应如下所示:

    DB::statement('INSERT INTO `products` (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE `updated_at` = NOW();');
    

    【讨论】:

    • 是的,我同意你的看法。语句查询是最快的解决方案。谢谢
    【解决方案2】:

    如果我正确理解您的问题,您应该在查询中指定重复的列并更新他们的updated_at 列。例如。

    DB::table('products')->where('duplicate_key', 'duplicate_value')->updateOrInsert(
         ['updated_at' => Carbon::now()],
    );
    

    【讨论】:

      【解决方案3】:

      试试这个更新

      products::where('id', $id)->update(['upc' => $request->input('upc'), 'upc' => $request->get('upc'),'name' => $request->get('name')]);
              return redirect()->back();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多