无法使用sequelize运行连接查询

时间:2017-03-15 13:55:07

标签: mysql sql node.js join sequelize.js

我需要使用sequelize运行join查询,我一直在sequelize doc阅读文档。但是当我运行以下代码片段时,我收到了一个错误。

    let channelUsersM = UserModel.get(); // Table name: channel_users
    let channelM = ChannelModel.get(); // Table name: channel

    channelUsersM.belongsTo(channelM, {as: 'channel',foreign_key: 'channel_id',targetKey:'id'});
    channelM.hasMany(channelUsersM,{foreign_key: 'channel_id'});

    channelUsersM.findAll({
        attributes: ['username'],
        where: {
            usertype: this.userType,
            channel: {
                name: channelName
            }
        },
        include: [channelM]
    }).then((r) => {
        resolve(r);
    }).catch((err) => {
        reject(err);
    });

错误说: channel is not associated to channel_users!

这可能是什么原因?我知道如何使用sequelize直接运行SQL查询,但我不想使用它。

为了便于理解,这是我用sequelize尝试的等效sql查询:

select cu.username from channel as ch left join 
channel_users as cu on ch.id = cu.channel_id 
ch.name = 'some-name' and cu.usertype = 'some-type';

如果需要,以下是模型的定义:

对于channel_users:

    channel_id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        field: 'channel_id'
    },
    userid: {
        type: Sequelize.INTEGER,
        field: 'userid'
    },
    username: {
        type: Sequelize.CHAR(255),
        field: 'username'
    },
    password: {
        type: Sequelize.TEXT,
        field: 'password'
    },
    usertype: {
        type: Sequelize.ENUM('user', 'moderator','speaker','owner'),
        field: 'usertype'
    }

对于频道:

    id: {
        type: Sequelize.INTEGER,
        field: 'id',
        autoIncrement: true,
        primaryKey: true
    },
    name: {
        type: Sequelize.CHAR(255),
        field: 'name'
    },
    display_name: {
        type: Sequelize.TEXT,
        field: 'display_name'
    },
    creatorid: {
        type: Sequelize.INTEGER,
        field: 'creatorid'
    },
    password: {
        type: Sequelize.TEXT,
        field: 'password'
    },
    createdAt: {
        type: Sequelize.DATE,
        field: 'createdAt'
    },
    modifiedAt: {
        type: Sequelize.DATE,
        field: 'modifiedAt'
    }

1 个答案:

答案 0 :(得分:1)

您已在alias关联中定义了belongsTo,因此您还需要在查询时在include属性中包含别名。此外,channel.name列值也应包含在查询的include对象中。

channelUsersM.findAll({
    attributes: ['username'],
    where: {
        usertype: this.userType
    },
    include: [
        {
            model: channelM,
            as: 'channel',
            attributes: [],
            where: { name: channelName }
        }
    ]
}).then((r) => {
    resolve(r);
}).catch((err) => {
    reject(err);
});

添加了attributes: []中的include,以防止从channel表格中返回任何字段(根据您的查询,您只需要username字段channel_users 1}}表)。