在 sequelize instanceMethods 中访问属性

accessing attributes in sequelize instanceMethods

我正在向 sequelize 模型添加一个实例方法。根据 the documentation 我应该可以引用 this.name,但我能看到的唯一值是 this.dataValues.name。我没有理由相信高质量的文档是错误的....但为什么会这样?

此外,没有可用的 setter 或 getter。 this.getDataValue / this.setDataValue 在 getters / setters 中工作,但不在 instanceMethods 中工作。

我在网上找不到任何相关示例 - 如果您知道读取(或更好地写入)这些值的项目,请将其添加到您的回复中。

module.exports = (sequelize: Sequelize, DataTypes: DataTypes) => {
  return sequelize.define<UserInstance, UserPojo>('User', {
      name: { type: DataTypes.STRING }
    }, {
      instanceMethods: {
        myMethod: (value) => {

          // this.name is undefined

          // this.dataValues.name IS defined ??

        }
      }, ...

正如您可能看到的,我正在使用 Typescript。我刚刚检查了生成的 Javascript,并立即看到了问题。

Typescript 将其放在模块的顶部:

var _this = this;

并引用了“_this”,而不是函数上下文中的那个——没有意识到这一点!一旦我将其更改为传统的 function() { } 语法,它就起作用了。所以,如果你使用的是打字稿,你可以这样做:

myMethod: function(value: type) => void {

}

也就是说,您不必放弃输入参数和 return 值。