Sequelize: Creating to-many relationships

蹲街弑〆低调 提交于 2019-12-12 02:23:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!