我正在用node,express和sequelize构建一个简单的数据库,我已经创建了我的模型,sequelize在我的数据库中创建了表。
我有模型用户和城市,具有多对多的关系。Sequelize创建了表用户,城市和连接表CitiesUsers:具有用户ID和城市ID。
我的问题是,当我创建一个新用户时,如何更新连接表?CityId属性在创建时被忽略。
//Models use
//City.hasMany(User);
//User.hasMany(City);
var user = User.build({
first_name: 'John',
last_name: 'Doe',
CityId: 5
});
user.save();
4条答案
按热度按时间r7xajy2e1#
在深入研究文档之后,我相信我已经找到了答案。
当创建多对多关系时,sequelize为每个模型创建get、set和add方法。
根据文档,假设用户和项目模型为多对多:http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-to-many-associations
这将添加方法getUsers、setUsers、addUsers到项目,以及getProjects、setProjects和addProject到用户。
因此,在我的例子中,我执行了以下操作,其中“city”是从City.find返回的特定City模型...
q3qa4bjr2#
创建City和User模型后,您可以创建模型的新示例,用作连接表。
kgqe7b3p3#
我发现,当我有一个实体引用另一个实体时,当(且仅当)它不存在时,我想创建被引用的实体,为此,我喜欢使用
findOrCreate()
。假设你在存储文章,每篇文章可以有任意数量的标签,你通常会想做的是:
1.遍历所有需要的标签,检查它们是否存在。如果不存在,创建它们。
1.一旦找到或创建了所有的标签,创建您的文章。
1.创建文章后,将其链接到您在步骤1中查找(或创建)的标记。
对我来说,这看起来像是:
jslywgbw4#
来自文档v3: