Sequelize:创建多对多关系 [英] Sequelize: Creating to-many relationships

查看:118
本文介绍了Sequelize:创建多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Node 中使用 Sequelize 并且有一个表名 UserAuth:

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.

一个User可以有多个Authto-manyAuth的关系.

A User can have many Auth's, to-many relationship with Auth.

一个Auth只能与User有一个Userto-one关系.

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` })
                }

此代码在 Auth 中创建一个字段,称为 userId.

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

我做错了什么?

推荐答案

试试这个:

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.

这篇关于Sequelize:创建多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆