如何在sequelize模型中插入外键 [英] How to insert foreign key in sequelize model

查看:175
本文介绍了如何在sequelize模型中插入外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在续篇中,我有一个用户模型和一个房屋模型.我也有一个包含{user_id,house_id}的UserHouse模型.如何在UserHouse模型中填充值.

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.

我浏览了续集文档,但不清楚.我需要知道如何在UserHouse模型中插入user_id和house_id.

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.

任何帮助将不胜感激.

已编辑:

还有一个问题:我还有一个模型HouseInfo,用于存储house_id(外键),我应该如何在数据库中存储此"house_id"外键以及如何关联模型.

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.

推荐答案

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/

这篇关于如何在sequelize模型中插入外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆