我在 Node 中使用 Sequelize 并有一个表名称 User
和 Auth
:
User
id
name
Auth:
id
token
我想向该模型添加关系。
用户
可以与Auth
拥有多个Auth
、对多
关系。
一个Auth
只能有一个用户
,与用户
是一对一
关系。
我的模型文件中有一个类实例,我用它来创建与以下代码的关系:
tableName: 'User',
classMethods: {
associate: function (models) {
user.belongsToMany(user, { through: { model: models.auth }, as: `user` })
}
此代码在 Auth
中创建一个名为 userId
的字段。
我希望得到的是以下内容:
User
id
name
auths //an array that will contain all instances of Auth by this User
Auth:
id
token
user //an object of User to whom this Auth object belongs to
我做错了什么?
最佳答案
尝试一下:
var User = sequelize.define('User', {
...
classMethods: {
associate: function (models) {
User.hasMany(models.Auth, {as: 'auths'});
}
}
};
var Auth = sequelize.define('Auth', {
...
classMethods: {
associate: function (models) {
Auth.belongsTo(models.User, {as: 'user'});
}
}
};
这会将 userId
列添加到 auth
表中。
要查询它(请注意查询中的 include
),您也可以执行相反的操作:
User.findOne({
include: [Auth]
})
您可能需要检查 one-to-many 的 Sequelize 文档, hasOne关系和hasMany , hasOne API 了解更多信息。
关于javascript - Sequelize : Creating to-many relationships,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822393/