sequelize / sequelize-typescript

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

Relations are not working properly while using multiple entity. Datas are duplicated. is it expected behaviour? #1147

Open GnanaprakashChandiran opened 2 years ago

GnanaprakashChandiran commented 2 years ago

Issue

Relations are not working properly while using multiple entity. Datas are duplicated. is it expected behaviour?

Versions

Issue type

Actual behavior

After run the query, the output is like,

[ { teamId: 1, name: 'Player 1' }, { teamId: 1, name: 'Player 3' }, ] The team records are duplicated, instead of map data in players proprty.

Expected behavior

[{ teamId: 1, players: [ { teamId: 1, name: 'Player 1' }, { teamId: 2, name: 'Player 2' } ] }, ]

Steps to reproduce

I have Team and Player table. The main table is Team and each team have multiple players.

Team table records:

[ { teamId: 1, name: 'Team 1' }, { teamId: 2, name: 'Team 2' } ]

Player table records:

[ { teamId: 1, name: 'Player 1' }, { teamId: 2, name: 'Player 2' }, { teamId: 1, name: 'Player 3' }, { teamId: 2, name: 'Player 4' } ]

@Table
class Player extends Model {
  @Column
  name: string

  @Column
  num: number

  @ForeignKey(() => Team)
  @Column
  teamId: number

  @BelongsTo(() => Team)
  team: Team
}

@Table
class Team extends Model {
  @Column
  name: string

@Column
  teamId: number

  @HasMany(() => Player)
  players: Player[]
}
That's all, sequelize-typescript does everything else for you. So when retrieving a team by find

Team.findAll({ include: [Player], raw:true, nest: true }).then((team) => {
  console.log('-=-=team-=-=', team);
})
n4an commented 2 years ago

try to remove frm class Team the @Column teamId: number because it is need to be id (primary key) wich is auto generated.

In example is like so https://github.com/RobinBuschmann/sequelize-typescript#model-association:

@Table
class Player extends Model {
  @Column
  name: string

  @Column
  num: number

  @ForeignKey(() => Team)
  @Column
  teamId: number

  @BelongsTo(() => Team)
  team: Team
}

@Table
class Team extends Model {
  @Column
  name: string

  @HasMany(() => Player)
  players: Player[]
}
GnanaprakashChandiran commented 2 years ago

try to remove frm class Team the @column teamId: number because it is need to be id (primary key) wich is auto generated.

In example is like so https://github.com/RobinBuschmann/sequelize-typescript#model-association:

@Table
class Player extends Model {
  @Column
  name: string

  @Column
  num: number

  @ForeignKey(() => Team)
  @Column
  teamId: number

  @BelongsTo(() => Team)
  team: Team
}

@Table
class Team extends Model {
  @Column
  name: string

  @HasMany(() => Player)
  players: Player[]
}

Mitch, I got the response. But the response format is different from what I expected.