mxmtsk
mxmtsk

Reputation: 4685

Sequelize: Custom Method with Where statement

I have two Models, a User Model and a Event Model. A user can have many Events.

I am still learning Sequelize and I'm wondering if it's possible to create like a custom method that easily get's me the upcoming Events (column date), so that I can do something like

User.getUpcomingEvents().then(() => {})

I'm coming from Laravel and Eloquent, and that was pretty easy to achieve over there but I'm struggeling to do it in Sequelize and the documentation is still a bit confusing for me.

Appreciate your tips :)

Upvotes: 1

Views: 1456

Answers (1)

piotrbienias
piotrbienias

Reputation: 7401

If you want to return events independent on the userId value, then you can use classMethods property when defining Model so that later you can call Model.<methodName>. In this case it would be User.getUpcomingEvents()

let User = sequelize.define('User', {
    // attributes...
}, {
    classMethods: {
        getUpcomingEvents: function(userId){
            return sequelize.models.Event.findAll({
                where: {
                    date: { $gt: new Date() },
                    UserId: userId // optional, if you want to return only events of given user
                }
            }).then(events => {
                return events;
            });
        }
    }
});

Otherwise, if you want to return upcoming events of given user, you can also use classMethod that would get userId as parameter, or, you can use instance method so that you can use it like userInstance.<methodName> like user.getUpcomingEvents()

instanceMethods: {
    getUpcomingEvents: function() {
        return this.getEvents({ where: { date: { $gt: new Date() } } }).then(events => {
            return events;
        });
    }
}

Please read the documentation concerning instance and class methods.

Upvotes: 1

Related Questions