简体   繁体   中英

Sequelize bulk insert with associations

I'm trying to bulk insert with associations, I have this 'Song' model which have one to many relationships with 'Genre' and 'Language' defined with the migrations CLI. Song:

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;
};

Language:

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;
};

Genre:

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;
};

I'm trying to bulk insert songs with languages and genres like this:

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

each song in the songs array is structured like this:

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

I'm ending up with a full songs table but genres and languages are empty What am I doing wrong? Thanks.

Unfortunately bulkCreate does not support include option like create do. You should use create in a cycle inside a transaction.

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

or you can use Promise.all to avoid using for .

Just in case anyone else got here from a search, starting from version 5.14 Sequelize added the option to use include option in bulkCreate as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM