BelongsToMany Association and Inserting to the DB using NodeJS Sequelize

Viewed 1077

I have 2 classes A and B , 3 tables A , B and AB

A.belongsToMany(B,as:'Bs', through: models.AB) 
B.belongsToMany(A,as:'As', through: models.AB)

Until now the associations are working im able to fetch A with B included and the other way around.

when im trying to create A , i am sending the JSON including the chosen B values. My JSON :

{
"name" : "A"
"Bs": [
        {"id_B" : 1},
        {"id_B" :2},
        {"id_B" :3}
    ]
}

My code to insert rows is :

A= await models.A.build(req.body, 
           {
             transaction:transaction,
             include:[
                { as:'Bs',required:true,model:models.B},
             ]
           }
)

What i expect the outcome to be is for sequelize to create rows inside AB table with the id's provided and the newly created id_A , but instead it is trying to create a row id_B inside table B and failing because of other attributes that cannot be null.

I have searched quite a while and tried multiple solutions, i understand that i am able to do this with two steps:

1)create A

2)A.addB()

Question:

1) is it possible to do it with one step ?

2) Am i doing something wrong with my JSON or its just not possible?

1 Answers

Using include in create/build means that we want to insert records to the included table. Therefore the following include means that records should be inserted to table B:

include:[
            { as:'Bs',required:true,model:models.B},
        ]

Since B values already exist in the DB, values should only be added to A and to AB so what is need is:

  1. Add the association between A and AB tables.
  2. Use AB in the create/build statement.

The code should look like this:

A.belongsToMany(B, { through: AB, as: 'Bs', foreignKey: 'id_A' }); // Not relevant for this use case
B.belongsToMany(A, { through: AB, as: 'As', foreignKey: 'id_B' }); // Not relevant for this use case
A.hasMany(AB, { as: 'ABs', foreignKey: 'id_A'} );

const a = await A.create({ 
    id: 1,
    ABs: [{ id_B: 22 }]
}, {
    include: [{
        model: AB,
        as: 'ABs'
    }]
});
Related