sequelize / sequelize-typescript

Decorators and some other features for sequelize
MIT License
2.79k stars 282 forks source link

Association fields are not functioning properly #1164

Open ghost opened 2 years ago

ghost commented 2 years ago

Issue

Versions

Issue type

Actual behavior

Association fields are undefined and hold nothing.

Expected behavior

Association fields hold the database object corresponding to the foreign key.

Steps to reproduce

See related code.

Related code

import {
    Column,
    Default,
    HasMany,
    Model,
    PrimaryKey,
    Table,
} from 'sequelize-typescript';
import Player from './Player';
import Question from './Question';

@Table
class Room extends Model {
    @PrimaryKey
    @Column
    roomNumber!: number;

    @Default('')
    @Column
    name!: string;

    @HasMany(() => Player)
    players!: Player[];

    @HasMany(() => Question)
    questions!: Question[];
}

export default Room;

When accessing room.players after getting a room from the Database, it's considered undefined. Same with any other kind of association. Example: I have the Session

import {
 Column, DataType, Default, ForeignKey, HasOne, Model, PrimaryKey, Table,
} from 'sequelize-typescript';
import Player from './Player';

@Table
class Session extends Model {
    @PrimaryKey
    @Column(DataType.STRING)
    socketId!: string;

    @Column
    playername!: string;

    @Default(0)
    @Column
    avatarId!: number;

    @HasOne(() => Player)
    player!: Player;

    @ForeignKey(() => Player)
    @Column
    playerId!: number;
}

export default Session;

And I have the player

import {
  AllowNull, Column, Default, Table, Model, BelongsTo, ForeignKey,
} from 'sequelize-typescript';
import Room from './Room';
import Session from './Session';
import { FrontendPlayer } from '../interfaces';

@Table
class Player extends Model {
  @Default(0)
  @AllowNull(false)
  @Column
  points!: number;

  @AllowNull(false)
  @Default(false)
  @Column
  isShowmaster!: boolean;

  @AllowNull(false)
  @Default(false)
  @Column
  buzzerPressed!: boolean;

  @ForeignKey(() => Session)
  @Column
  sessionId!: string;

  @BelongsTo(() => Session)
  session!: Session;

  @ForeignKey(() => Room)
  @Column
  roomNumber!: number;

  @BelongsTo(() => Room)
  room!: Room;
}

export default Player;

The session is undefined, the room is undefined. The sessionId is NOT undefined. The roomNumber is also NOT undefined.

ephys commented 2 years ago

The problem you're experiencing (it's been a couple months so I hope you found a resolution since then) is the same as this one: https://github.com/RobinBuschmann/sequelize-typescript/issues/778