Jor*_*son 1 javascript sequelize.js
我想知道是否有一种方法可以通过播种器批量插入数据以添加到数据库中,但要排除任何已存在的条目。
例如: 如果数据库中有名为 John 的用户,我运行一个播种器将用户添加到数据库中,并且播种器中有一个包含名称 John 的条目,它将跳过该条目,因为它已经存在。
您可以将public static asyncbulkCreate(records: Array, options: object): Promise<Array>方法与options.ignoreDuplicates
.
忽略主键的重复值?(MSSQL 或 Postgres < 9.5 不支持)
unique
向该字段添加约束非常重要name
。
"sequelize": "^5.21.3"
这是使用和 的示例postgres:9.6
:
import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';
class User extends Model {}
User.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
unique: true,
},
},
{ sequelize },
);
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
await User.create({ name: 'John' });
// insert multiple instances in bulk
await User.bulkCreate([{ name: 'teresa teng' }, { name: 'slideshowp2' }, { name: 'John' }], {
fields: ['name'],
ignoreDuplicates: true,
});
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
Run Code Online (Sandbox Code Playgroud)
我们首先播种一个 user( John
),然后批量插入多个用户。John
数组中存在重复的 user( )。关键的SQL语句是:ON CONFLICT DO NOTHING
,这意味着如果唯一name
冲突,则插入操作将不执行任何操作。
执行结果:
Executing (default): DROP TABLE IF EXISTS "User" CASCADE;
Executing (default): DROP TABLE IF EXISTS "User" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "User" ("id" SERIAL , "name" VARCHAR(255) UNIQUE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'User' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "User" ("id","name") VALUES (DEFAULT,$1) RETURNING *;
Executing (default): INSERT INTO "User" ("id","name") VALUES (DEFAULT,'teresa teng'),(DEFAULT,'slideshowp2'),(DEFAULT,'John') ON CONFLICT DO NOTHING RETURNING *;
Run Code Online (Sandbox Code Playgroud)
执行后查看数据库:
node-sequelize-examples=# select * from "User";
id | name
----+-------------
2 | teresa teng
3 | slideshowp2
1 | John
(3 rows)
Run Code Online (Sandbox Code Playgroud)