Sequelize.js-如何在不定义关系表的情况下从多对多关联中获取数据

时间:2019-09-17 16:28:56

标签: node.js orm sequelize.js

我在Sequelize.js中定义了两个数据库模型:

用户:

module.exports = (sequelize, DataTypes) => {
    const model = sequelize.define('User', {
        email: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        },
        password: {
            type: DataTypes.CHAR,
            length: 60,
            allowNull: false
        }
    }
    });

    model.associate = models => {
        model.belongsToMany(models.Role, {
            hooks: true,
            through: 'user_roles'
        })
    };

    return model;
};

角色:

module.exports = (sequelize, DataTypes) => {
    const model = sequelize.define('Role',
        {
            name: {
                type: DataTypes.STRING,
                unique: false,
                allowNull: false
            }
        }
    );

    model.associate = models => {
        model.belongsToMany(models.User, {
            hooks: true,
            through: 'user_roles'
        });
    };

    return model;
};

user_roles是自动创建的。当我查询User时,我也想在结果中包含roles数组。我是这样的:

const user = await User.findOne({
            where: {
                email: data.email
            },
            attributes: ['id', 'password', 'email'],
            include: [{
                model: 'user_roles',
                attributes: ['key']
            }]
        });

但是我收到错误消息:TypeError: include.model.getTableName is not a function意味着model:必须是真实模型,不能仅使用表名。但是如何从该表中获取数据呢?

我也尝试过:

const user = await User.findOne({
            where: {
                email: data.email
            },
            attributes: ['id', 'password', 'email'],
            include: [{
                model: Role,
                attributes: ['key']
            }]
        });

但这给我带来了太多数据的奇怪对象:

Roles: [
  {
    key: 'USER',
    user_roles: {
      createdAt: 2019-09-17T16:19:44.000Z,
      updatedAt: 2019-09-17T16:19:44.000Z,
      RoleId: 1,
      UserId: 4
    }
  }
]

我只需要key: 'USER'

1 个答案:

答案 0 :(得分:0)

尝试添加through: { attributes: [] }

const user = await User.findOne({
        where: {
            email: data.email
        },
        attributes: ['id', 'password', 'email'],
        through: { attributes: [] },
        include: [{
            model: Role,
            attributes: ['key']
        }]
    });