带有sequelizejs的第二个表上带有条件的SQL JOIN

时间:2017-05-27 23:32:09

标签: mysql join sequelize.js

我有以下型号:

const User = sequelize.define('user', {
    name: Sequelize.TEXT,
    avatar: Sequelize.TEXT,
});

const Event = sequelize.define('event', {
    title: Sequelize.STRING,
    description: Sequelize.TEXT,
    timestamp: Sequelize.DATE,
});

const EventUser = sequelize.define('event_user', {});

Event.hasMany(EventUser);
EventUser.belongsTo(User);

所以EventUser保存我的特定活动的参与者名单。

我试图查询用户X参与的所有事件:

let events = await Event.findAll({
    include: [
        {model: EventUser, include: [{model: User, where: {id: 1}}]}
    ],
});

但它不会获取该事件的其他参与者列表。不知道怎么做到这一点,谢谢!

1 个答案:

答案 0 :(得分:1)

正确的方法是定义用户和事件之间的多对多关系

User.belongsToMany(Event, {through: 'EventUser'});
Event.belongsToMany(User, {through: 'EventUser'});

然后,您可以获得某些用户的所有事件:

User.findById(userId).then(function(user){
    return user.getEvents();
}).then(function(events){
    //here's events
});

或通过一个查询:

Event.findAll({
    include: [{
        model: User,
        where: {id: userId}
    }]
}).then(function(events){
    //here's events
});