[英]How to add many to many association in existing models in sequelize node.js?
I want to add many to many association in my node app using sequelize.我想使用 sequelize 在我的节点应用程序中添加多对多关联。 I am new in sequelize ORM.
我是续集 ORM 的新手。
I have a eixsting model user.js.我有一个 eixsting 模型 user.js。 I want to create new model project and add want to many to many association
我想创建新的模型项目并添加想要的多对多关联
For that I run sequelize create table and migration created Now in association part what I do that many to many association created为此,我运行 sequelize create table 和 migration created 现在在关联部分中我做了多对多关联创建
I find multiple these to do that我找到多个这些来做到这一点
Project.belongsToMany(User, {through: 'UserProject'});
But Where I write User.belongsToMany(Project, {through: 'UserProject'});
但是我在哪里写
User.belongsToMany(Project, {through: 'UserProject'});
because user model is alreaady existing因为用户模型已经存在
Second thing I want to know either UserProject
automatically created by this or need to manually create it?第二件事我想知道
UserProject
自动创建的UserProject
还是需要手动创建它?
It is a good practice to use sequelize-cli
and use the sequelize init
tool, which creates a file which gathers together all your models and creates associations between them.使用
sequelize-cli
和sequelize init
工具是一个很好的做法,它会创建一个文件,将所有模型聚集在一起并在它们之间创建关联。 The association is done via class method associate
, which should be implemented in all of your models (having association to other ones).关联是通过类方法
associate
,它应该在您的所有模型中实现(与其他模型有关联)。
This method could look like this (in case of User
model):此方法可能如下所示(在
User
模型的情况下):
classMethods: {
associate: function(models){
this.belongsToMany(models.Project, { through: 'UserProject' });
}
}
And equivalent in the Project
model:和
Project
模型中的等价物:
classMethods: {
associate: function(models){
this.belongsToMany(models.User, { through: 'UserProject' });
}
}
If you do not want to add any other extra fields to the UserProject
table, it will be created automatically with fields UserId
and ProjectId
(if you use the sequelize.sync()
method - otherwise you have to create the table in migration file).如果您不想向
UserProject
表添加任何其他额外字段,它将使用字段UserId
和ProjectId
自动创建(如果您使用sequelize.sync()
方法 - 否则您必须在迁移文件中创建表)。 In other case, when you want to add other fields, you would have to create such a model itself.在其他情况下,当您想要添加其他字段时,您必须自己创建这样的模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.