OutOfMind
OutOfMind

Reputation: 924

How to insert foreign key in sequelize model

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.

Upvotes: 1

Views: 7058

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28788

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/

Upvotes: 2

Related Questions