简体   繁体   中英

Sequelize.js - How to get data from many-to-many association without defined Relation table

I have defined two database models in Sequelize.js :

User:

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;
};

Role:

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;
};

Table user_roles is create automatically. When I query for User I also want to include roles array in the result. I do so like this:

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

But I get error: TypeError: include.model.getTableName is not a function what means that model: must be real model and can't do just table name. But how to get data from this table then?

I also tried:

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

But this gives me weird object with too much data:

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

I need just the key: 'USER'

Try adding through: { attributes: [] } .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM