【问题标题】:Sequelize: Custom Method with Where statementSequelize:带有 Where 语句的自定义方法
【发布时间】:2017-03-29 22:22:55
【问题描述】:

我有两个模型,一个User 模型和一个Event 模型。一个用户可以有许多事件。

我仍在学习 Sequelize,我想知道是否有可能创建一个自定义方法来轻松获取即将到来的事件(列 date),以便我可以做类似的事情

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

我来自 Laravel 和 Eloquent,在那里很容易实现,但我在 Sequelize 中努力做到这一点,文档对我来说仍然有点混乱。

感谢您的提示 :)

【问题讨论】:

    标签: javascript sequelize.js


    【解决方案1】:

    如果要返回独立于userId 值的事件,则可以在定义模型时使用classMethods 属性,以便稍后调用Model.<methodName>。在这种情况下,它将是 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;
                });
            }
        }
    });
    

    否则,如果你想返回给定用户的即将发生的事件,你也可以使用classMethod,它会得到userId作为参数,或者,你可以使用实例方法,这样你就可以像userInstance.<methodName>一样使用它像@987654329 @

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

    请阅读documentation 关于实例和类方法。

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 2014-11-07
      • 2015-05-25
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      相关资源
      最近更新 更多