问题
I am using Sequelize in Node and have a table name User and Auth:
User
id
name
Auth:
id
token
I would like to add relationships to this model.
A User can have many Auth's, to-many relationship with Auth.
An Auth can only have one User, to-one relationship with User.
I have a class instance in my model file that I am using to create relationships with the following code:
tableName: 'User',
classMethods: {
associate: function (models) {
user.belongsToMany(user, { through: { model: models.auth }, as: `user` })
}
This code creates a field in Auth, called userId.
What I am hoping to get is the following:
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
What am I doing wrong?
回答1:
Give this a try:
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'});
}
}
};
This'll add a userId column to the auth table.
To query it you'd do (note the include in the query) you can also do it vice-versa:
User.findOne({
include: [Auth]
})
You might want to check the sequelize docs for one-to-many, hasOne relationships and the hasMany, hasOne API for more info.
来源:https://stackoverflow.com/questions/39822393/sequelize-creating-to-many-relationships