How to insert foreign key in sequelize model

試著忘記壹切 提交于 2021-01-28 12:12:04

问题


I have a User model and a Houses model in sequelize. I also have a UserHouse model that contains {user_id, house_id}. How do I populate values in the UserHouse model.

I went through the sequelize documentation but could not get a clear idea. I need to know, how to insert user_id and house_id in UserHouse model.

I also cannot understand what associations should I use between these models.

Any help will be appreciated.

Edited:

One More issue: I have one more model HouseInfo that stores house_id (foreign key), how should I store this "house_id" foreign key in db and how should I associate the models.


回答1:


User.belongsToMany(House, { through: UserHouse });
House.belongsToMany(User, { through: UserHouse });

user.addHouse(house);
house.setUsers([user1, user2])

http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-to-many-associations http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/



来源:https://stackoverflow.com/questions/33911597/how-to-insert-foreign-key-in-sequelize-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!