【问题标题】:Sequelize bulk insert with associations使用关联对批量插入进行续集
【发布时间】:2021-01-03 09:58:59
【问题描述】:

我正在尝试批量插入关联, 我有这个“歌曲”模型,它与迁移 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);
});

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

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

我最终得到了一张完整的歌曲表,但流派和语言为空 我究竟做错了什么? 谢谢。

【问题讨论】:

    标签: node.js sequelize.js associations bulkinsert


    【解决方案1】:

    不幸的是,bulkCreate 不支持 include 选项,如 create 支持。 您应该在事务内的循环中使用create

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2018-04-08
        • 1970-01-01
        • 2014-06-30
        • 2016-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-05
        • 1970-01-01
        相关资源
        最近更新 更多