sequelize-typescript icon indicating copy to clipboard operation
sequelize-typescript copied to clipboard

Association fields are not functioning properly

Open Nickland opened this issue 4 years ago • 1 comments

Issue

Versions

  • sequelize: 6.12.0-beta.3
  • sequelize-typescript: 2.1.1
  • typescript: 4.5.4

Issue type

  • [x] bug report
  • [ ] feature request

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.

Nickland avatar Dec 21 '21 21:12 Nickland

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

ephys avatar Apr 07 '22 13:04 ephys