selfclose
selfclose

Reputation: 121

Sequelize js: create/update with foreign key

Just want to CRUD and understand how it work.

model.wallet.belongsTo(model.users);

model.wallet.sync({force: true}).then(function () {
    return model.wallet.create({
        balance: 300,
        users: {id:1}
    }, {
        include: [ model.users ]
    })
});

I tried include: [ {model: model.users} ] But still got (NULL)

If you have solution and some example, It should be nice.

Upvotes: 2

Views: 9627

Answers (1)

piotrbienias
piotrbienias

Reputation: 7411

According to the example in Sequelize documentation

Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team.

By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name.

Assuming that those models are called player and team, and the primary key in model team is id. It means that if you use belongsTo on specified model (without any additional option), it will create an attribute with name <related_model_name><related_model_primary_key>, so if your user model is called users and it's primary key is id, then the foreign key created in wallet model would be called usersId.


If you want to create new wallet and assign it to user, you need to specify proper foreign key field in create attributes

model.wallet.create({
    balance: 300,
    usersId: 1
});

Upvotes: 3

Related Questions