且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Sequelize:创建多对多关系

更新时间:2022-12-30 18:27:23

试试这个:

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 表中.

This'll add a userId column to the auth table.

要查询你会做的(注意查询中的include),你也可以反之:

To query it you'd do (note the include in the query) you can also do it vice-versa:

User.findOne({
    include: [Auth]
})

您可能需要查看 的续集文档一对多hasOne 关系和hasManyhasOne API 了解更多信息.

You might want to check the sequelize docs for one-to-many, hasOne relationships and the hasMany, hasOne API for more info.