Sequelize: Creating To-many Relationships
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 ma
Solution 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.
Post a Comment for "Sequelize: Creating To-many Relationships"