如何通过一次查询将数组数据插入数据库的唯一字段?

How to insert array data with one query to unique field of database?

我有用于将数据数组添加到数据库的示例工作代码:

迁移:

Schema::create('words', function (Blueprint $table) {
    $table->increments('id');
    $table->string('word')->unique();
    $table->integer('type')->default(0);
    $table->integer('is_active')->default(0);
    $table->timestamps();
});

代码:

$words = [
    ['word' => 'apple',   'type' => 1, 'is_active' => 1],
    ['word' => 'peach',   'type' => 1, 'is_active' => 1],
    ['word' => 'banana',  'type' => 1, 'is_active' => 1]
];

foreach ($words as $word) {
    Word::updateOrCreate($word);
}

在我的数据库中,单词将是唯一的,对于唯一插入,我使用 updateOrCreate() method. In my code have 3 queries to database. How I can insert unique array of data to database with one query? I seen to updateOrInsert(),但使用它我也无法通过一次查询将单词插入数据库。

你应该试试下面的代码。

DB::table('words')->insert([
            ['word' => 'apple',   'type' => 1, 'is_active' => 1],
            ['word' => 'peach',   'type' => 1, 'is_active' => 1],
            ['word' => 'banana',  'type' => 1, 'is_active' => 1],
        ]);

您可以使用 insert-on-duplicate.

通过一个原始数据库查询来完成此操作

未测试,但可能是这样的:

$sql = 'INSERT INTO words (word, type, is_active) VALUES ';

foreach($words as $row) {
    $sql .= '('.$row['word'].','.$row['type'].','.$row['is_active'].') ';
}

$sql .= 'ON DUPLICATE KEY UPDATE word = VALUES(word)';

DB::statement($sql);

您可能还想将时间戳也放在那里。

你不能开箱即用,因为 Eloquent 不支持 INSERT IGNOREON DUPLICATE KEY 构造。

您可能需要 this package provides

这适用于您的用例,但我不太喜欢它使用的静态方法。

另外请记住,这会产生 MySQL 个查询并且(就像使用 DB::table('x'))它没有使用 Eloquent,所以它不会在模型上使用 set/update 时间戳, 没有事件触发等