【问题标题】:How can I tell typescript that the getAssociation function exists in a Sequelize model?如何告诉 typescript getAssociation 函数存在于 Sequelize 模型中?
【发布时间】:2021-01-31 01:33:40
【问题描述】:

我有以下代码:

interface TableBAttributes {
    TableBId: number;
}

interface TableAAttributes {
    TableAId: number;
    TableB: TableB;
}

class TableA extends Model<TableAAttributes> {}
TableA.init({
   TableAId: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true
   },
   TableB: {
      DataTypes.INTEGER,
      references: {
         model: TableB,
         key: 'tableB_id'
      },
      field: 'tableB_id'
   }
}, {
  sequelize,
  modelName: 'TableA',
  tableName: 'TableA'
});

TableA.belongsTo(TableB, {
   foreignKey: 'tableB_id',
   as: 'TableB'
});

class TableB extends Model<TableBAttributes> {};
TableB.init({
    TableBId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true
    }
}, {
   sequelize,
   modelName: 'TableB',
   tableName: 'TableB'
});

(async () => {
   const test = await TableA.findByPk(1);
   const relatedTableB = await test.getTableB();
   console.log(relatedTableB);
})();

如果我运行此代码,一切都会正常运行,并且我会从查询中返回关联的 TableB。我唯一的问题是,打字稿抱怨 test.getTableB() 函数不存在,因为这个方法是由 Sequelize 创建的。

我如何告诉 typescript 这个方法存在?

【问题讨论】:

    标签: typescript sequelize.js sequelize-typescript


    【解决方案1】:

    如果它适合你,请检查它。

    了解更多info

    import {
      Model,
      HasOneGetAssociationMixin,
    } from "sequelize";
    
    interface TableBAttributes {
      TableBId: number;
    }
    
    interface TableAAttributes {
      TableAId: number;
    }
    
    class TableA extends Model<TableAAttributes> {
      public getTableB!: HasOneGetAssociationMixin<TableB>
    }
    
    class TableB extends Model<TableBAttributes> { }
    
    TableA.belongsTo(TableB, {
      foreignKey: 'tableB_id',
      as: 'TableB'
    });
    
    (async () => {
      const test = await TableA.findByPk(1);
      const relatedTableB = await test.getTableB();
      console.log(relatedTableB);
    })();
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2020-03-18
      • 1970-01-01
      • 2019-08-05
      • 2020-07-27
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多