How to create a record in nested tables in sequelize?

Asked

Viewed 19 times

0

I have a users table and a posts table:

    const users = sequelize.define(users, {
nomeuser : { 
sequelize.STRING
})

users.sync() 

const post = sequelize.define(postagens,{

potagens:{
type: sequelize.STRING
}

})

post.sync()

users.hasMany(posts, {foreignKey: "postid"})

The two tables relate in the sense that each user may have many posts but I can’t create a post with the user that has already been created.

Trying to be clearer, I register a user only once and then I just have to record the posts that it makes recording clear the identity of who posted with foreignKey more not being able to do this:

const idpesq = users.findAll({
attributes: ["id"],
where: {
nomeuser: "João da Silva"
} 
}).then(function(id){
return id
})

const criarpostagem = post.create({

postId: idpesq.id,
postagens: " Qualquer coisa que o usuario venha postar "


})

This way I can create the record of the post in the database but the foreign key "postid" is like Null which makes the record has no relation to the user who created. How do I create this instance?

I have read and reread the documentation of the sequelize but I did not understand anything, I thank anyone who can help.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.