sequelize/sequelize-typescript

Multiple relation to the same model problem

loss-and-quick opened this issue · 0 comments

Issue

Versions

  • sequelize: 6.31.0
  • sequelize-typescript: 2.1.5
  • typescript: 5.0.4

Issue type

  • bug report
  • feature request

Actual behavior

I want to make a link between the same model, but when you create an instance of a model an associations are not set
But at the subsequent reception of all objects from the database, all is well and all associations are created

Expected behavior

Just clarify a problem?

Steps to reproduce

See below

Related code

tsconfig:

{
    "extends": "ts-node/node16/tsconfig.json",
    "compilerOptions": {
        "module": "Node16",
        "target": "ES6",
        "moduleResolution": "node16",
        "resolveJsonModule": true,    
        "strictNullChecks": true,
        "strictFunctionTypes": true,
        "skipLibCheck": true,
        "outDir": "dist",
        "rootDir": "src",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "strictPropertyInitialization": false
    },
    "include": [
        "src"
    ],
    "exclude": [
        "node_modules",
        "src/**/*.test.ts"
    ],
    "ts-node": {
        "pretty": true,
        "esm": true
    }
}
// Worker Model
@Table({
    tableName: 'worker',
})
export class WorkerModel
    extends Model<WorkerModel, WorkerCreationAttributes>
    implements Worker
{
    @PrimaryKey
    @Column(DataTypes.INTEGER)
    public readonly telegramID: number;

    ...

    @HasMany(() => JoinedGroupModel)
    joinedGroup: JoinedGroupModel[];

    @ForeignKey(() => WorkerModel)
    @Column(DataTypes.INTEGER)
    public refferalID?: number;

    @BelongsTo(() => WorkerModel, 'refferalID')
    refferal?: ReturnType<() => WorkerModel>;
}
// Database.ts somewhere in class
// this function works fine
async getWorkers(): Promise<Worker[]> {
        return await WorkerModel.findAll({
            include: [{ all: true }],
        });
};
// function below doesnt set up any associations
async createWorker(_worker: WorkerCreationAttributes): Promise<Worker> {
        const worker = await WorkerModel.create(_worker, {
            include: [WorkerModel],
        });
        return worker;
 }