12

在我的一个基于某些指标存储聚合计数的工作脚本中,我没有使用 Eloquent,因为查询有点复杂,而且使用查询构建器很容易编写。我目前正在从数据库中获取值,我需要在数据库中插入/更新它。可以使用 Query Builder 实现的 save() 方法进行 upsert 操作吗?还是我每次都需要检查这个条目是否在数据库中?

我总共有 100,000 个条目,并希望将其作为日常工作运行。因此,如果我需要检查数据库中是否存在特定条目,我需要多次访问数据库。有没有替代解决方案?

我正在考虑创建两个模型类,一个使用 Eloquent,一个使用查询生成器。我可以在 Eloquent 模型中使用我的自定义查询吗?

4

3 回答 3

14

Eloquent 有updateOrCreate()方法可以让你做你想做的事。但是查询生成器没有类似的方法。

您可以使用 Query Builder 构建原始查询并使用INSERT ... ON DUPLICATE KEY UPDATE作为 upsert 解决方案。

于 2016-06-10T06:20:22.533 回答
14

现在(2020 年 10 月 6 日),Laravel(v8.10.0) 已经原生upsert支持。https://github.com/laravel/framework/pull/34698

DB::table('users')->upsert([
    ['id' => 1, 'email' => 'taylor@example.com'],
    ['id' => 2, 'email' => 'dayle@example.com'],
], 'email');
于 2020-11-25T02:36:15.430 回答
2

Eloquent 有一个名为 的方法updateOrCreate,可以像这个例子一样使用:

<?
$flight = Flight::updateOrCreate(
    [
       'code' => '156787', 
       'destination' => 'COL'
    ],
    [
       'code' => '156787', 
       'destination' => 'COL',
       'price' => 99, 
       'discounted' => 1,
    ],
);
  1. 搜索code并且destination可以通过您最好的方式来识别您的行。
  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 = [])
于 2020-09-01T23:20:30.870 回答