Gilad Novik
Gilad Novik

Reputation: 4604

SQL JOIN with condition on second table with sequelizejs

I have the following models:

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

So EventUser holds my list of participants for a specific event.

I'm trying to query for all events where user X is participating:

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

But it won't fetch the list of other participants for that event. Not sure how to achieve that, thanks!

Upvotes: 0

Views: 43

Answers (1)

Yrysbek Tilekbekov
Yrysbek Tilekbekov

Reputation: 2775

Right way is to define many-to-many relation between Users and Events

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

Then, you can get all events of some user like this:

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

Or through one query:

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

Upvotes: 1

Related Questions