Sequelize打字稿'HasManyCreateAssociationMixin'不是一个函数

时间:2019-10-07 16:15:50

标签: node.js typescript sequelize.js

我在sequelize-typescript中有一个模型,Door.ts:

import { Table, Model, Column, AutoIncrement, PrimaryKey, ForeignKey, DataType, AllowNull, BelongsTo, HasMany } from 'sequelize-typescript';
import { Location } from '@modules/location';
import { AkilesServiceV1, AkilesServiceV0, IDoorService } from '@services/DoorService';
import { BelongsToGetAssociationMixin } from 'sequelize/types';
import { DoorLog } from '@modules/door_log';
import { HasManyCreateAssociationMixin } from 'sequelize';

@Table({ tableName: 'door' })
class Door extends Model<Door> {
    @PrimaryKey
    @AutoIncrement
    @Column
    id!: number;

    @AllowNull(false)
    @Column
    type!: string;

    @Column
    button_id!: string;

    @Column
    gadget_id!: string;

    @Column
    action_id!: string;

    @AllowNull(false)
    @Column(DataType.ENUM('vehicular','pedestrian'))
    access_type!: 'vehicular' | 'pedestrian';

    @AllowNull(false)
    @Column
    description_tag!: string;

    @Column(DataType.VIRTUAL)
    description!: string;

    @ForeignKey(() => Location)
    @AllowNull(false)
    @Column
    location_id!: number;

    @BelongsTo(() => Location)
    location!: Location;

    @HasMany(() => DoorLog)
    door_logs!: DoorLog[];

    public getLocation!: BelongsToGetAssociationMixin<Location>;
    public createDoorLog!: HasManyCreateAssociationMixin<DoorLog>;

    public async open () {
        let doorService: IDoorService;
        switch(this.type) {
            case 'akiles-v0':
                doorService = new AkilesServiceV0();
                break;
            case 'akiles-v1':
                doorService = new AkilesServiceV1();
                break;
            default:
                doorService = new AkilesServiceV1();
                break;
        }

        //await doorService.open(this);

        return await this.createDoorLog({ door_id: this.id, timestamp: new Date() });

    }

    public async getParking() {
        const location: Location = await this.getLocation();
        return await location.getParking();
    }
}

export default Door

如您所见,它具有与Mixins相关的这两个功能:

public getLocation!: BelongsToGetAssociationMixin<Location>;
public createDoorLog!: HasManyCreateAssociationMixin<DoorLog>;

第一个可以像这样await this.getLocation()完美地使用它。但是,当我这样称呼它时,第二个:await this.createDoorlog ({door_id: this.id, timestamp: new Date ()})返回以下错误:

TypeError: this.createDoorLog is not a function

我也尝试了不带参数的函数,但是得到了相同的结果。我不明白为什么两个函数虽然创建时几乎完全相同,但行为却不同。我是否缺少HasManyCreateAssociationMixin的东西?

谢谢。

1 个答案:

答案 0 :(得分:0)

因为当我不可避免地再次遇到这个问题时,又被同样的问题所困扰。答案是在 @HasMany mixin 中添加“as”。 Sequelize 似乎在驼峰类中存在问题。

所以在这种情况下添加

@HasMany(() => DoorLog, options: {as: "doorLog" })
    door_logs!: DoorLog[];

或者类似的东西应该允许你使用这个mixin