Skip to content
Advertisement

How to fill the middle table of an n:m association with the methode fooInstance.createBar() with Sequelize

I want to fill the data into a N:M jointure table with the methods provided by sequelize. As my data is in allowNull: false, i can’t add the data afterward :/

Here an exemple of code/BDD:

UML

my table a:

var A = sequelize.define('A', {
    id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false
    },
    someDataA: {
            type: DataTypes.INTEGER,
            allowNull: false
    },
})

A.associate = function(models) {
        A.belongsToMany(models.B, { 
            through: models.C, 
            foreignKey: 'a_id',
            otherKey: 'b_id',
            as: 'C'
        });
    }

my table b:

var B = sequelize.define('B', {
    id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false
    },
    someDataB: {
            type: DataTypes.INTEGER,
            allowNull: false
    },
})
B.associate = function(models) {
        B.belongsToMany(models.A, { 
            through: models.C, 
            foreignKey: 'b_id',
            otherKey: 'a_id',
            as: 'C'
        });
    }

my table c:

var C = sequelize.define('C', {
    a_id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            allowNull: false
    },
    b_id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            allowNull: false
    },
    JointedData: {
            type: DataTypes.INTEGER,
            allowNull: false
    },
})

C.associate = function(models) {
        C.belongsTo(models.A, {
            as: 'A',
            foreignKey: 'a_id'
        });
        C.belongsTo(models.B, {
            as: 'B',
            foreignKey: 'b_id'
        });
    }

I want to be able to do something like this:

fooAInstance.createB({somdeDataB: 15}, /* define here the data into JointedData */ {JointedData: 99});

How can i achieve something like that???

Thx for your time and answers!

Advertisement

Answer

You should indicate through option like this:

await fooAInstance.createB({somdeDataB: 15}, { through: { JointedData: 99 } })

See Advanced Many-to-Many

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement