NodeJS 将大容量插入与关联顺序化

zqry0prt  于 2023-02-03  发布在  Node.js
关注(0)|答案(2)|浏览(137)

我正在尝试批量插入关联,我有这个'歌曲'模型,它与'流派'和'语言'有一个到多个关系定义与迁移CLI.歌曲:

module.exports = (sequelize, DataTypes) => {
    class Song extends Model {
     
        static associate(models) {
            // define association here
            Song.hasMany(models["Language"])
            Song.hasMany(models["Genre"])
        }
    };
    Song.init({
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: DataTypes.STRING,
        energy: {type: DataTypes.FLOAT, allowNull: false},
        valence: {type: DataTypes.FLOAT, allowNull: false}
    }, {
        sequelize,
        modelName: 'Song',
        timestamps: true
    });
    return Song;
};

语言:

module.exports = (sequelize, DataTypes) => {
    class Language extends Model {
        static associate(models) {
            // define association here
            models["Language"].belongsTo(models["Song"])
        }
    };
    Language.init({
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: DataTypes.STRING
    }, {
        sequelize,
        modelName: 'Language',
        indexes: [{unique: true, fields: ['name']}]
    });
    return Language;
};

类型:

module.exports = (sequelize, DataTypes) => {
    class Genre extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            // define association here
            models["Genre"].belongsTo(models["Song"])
        }
    };
    Genre.init({
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: DataTypes.STRING
    }, {
        sequelize,
        modelName: 'Genre',
        indexes: [{unique: true, fields: ['name']}]
    });
    return Genre;
};

我正在尝试批量插入语言和类型如下的歌曲:

Song.bulkCreate(songs, {
    include: [Genre,Language]
}).then(() => {
    const result = {
        status: "ok",
        message: "Upload Successfully!",
    }
    res.json(result);
});

歌曲数组中的每首歌曲的结构如下:

{
    name: "abc",
    genres: [{name: "abc"}],
    languages: [{name: "English"}],
    energy:  1,
    valence: 1
}

我得到了一个完整的歌曲列表,但是流派和语言都是空的我做错了什么,谢谢.

5w9g7ksd

5w9g7ksd1#

以防其他人通过搜索找到这里,从version 5.14开始Sequelize添加了使用include option in bulkCreate的选项,如下所示:

await Song.bulkCreate(songsRecordsToCreate, {
    include: [Genre,Language]
})
but5z9lq

but5z9lq2#

编辑2023年2月2日

正如上面none的回答,从v5.14.0开始,include选项现在在bulkInsert上可用。
不幸的是bulkCreate不像create那样支持include选项。您应该在事务内循环使用create

const transaction = ...
for (const song of songs) {
  await Song.create(song, {
    include: [Genre,Language]
  }, { transaction })
}
await transaction.commit()

或者您可以使用Promise.all来避免使用for

相关问题