Wednesday, 30 January 2019

BelongsToMany Association and Inserting to the DB using NodeJS Sequelize

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?



from BelongsToMany Association and Inserting to the DB using NodeJS Sequelize

No comments:

Post a Comment