【问题标题】:How to add multiple relations one at a time in TypeORM如何在 TypeORM 中一次添加多个关系
【发布时间】:2020-05-02 06:47:21
【问题描述】:

所以我已经为此苦苦挣扎了一段时间,我的代码库中有这么多的关系。在用户和赔率之间。我希望用户能够添加赔率

用户实体:

 @Entity()
    @Unique(['username'])
    export class User extends BaseEntity {
      @PrimaryGeneratedColumn()
      id: number;

      @Column()
      username: string;

      @Unique(['email'])
      @Column()
      email: string;

      @Column()
      password: string;

      @Column({ nullable: true })
      customerId: string;

      @ManyToMany(type => Odds, odds => odds.user)
      @JoinTable()
      odds: Odds[];

      @Column()
      salt: string;

      async validatePassword(password: string): Promise<boolean> {
      const hash = await bcrypt.hash(password, this.salt);
      return hash === this.password;
  }
}

赔率实体:

@Entity()
export class Odds extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  hometeam: string;

  @Column()
  awayteam: string;

  @Column()
  hometeamLogo: string;

  @Column()
  awayteamLogo: string;

  @Column()
  bet: string;

  @Column({ type: 'real' })
  value: string;

  @Column()
  stake: number;

  @Column({ type: 'real' })
  bookieOdds: string;

  @ManyToMany(type => User, user => user.odds)
  user: User[];
}

当我尝试添加这样的关系时

async addOddsToUser(user: User, oddsId: number): Promise<void> {
    const id = user.id;
    const userDB = await this.userRepository.findOne({ id });
    const odds = await this.oddsRepository.findOne({ id: oddsId });
    userDB.odds = [odds];
    userDB.save();
  }

在关联表中它确实第一次添加了关系,但如果我再添加一个它会覆盖第一个关系,我也尝试了 userDB.odds.push(odds);这不起作用。

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript typescript orm nestjs typeorm


    【解决方案1】:

    问题是您的addOddsToUser 函数每次都会用一个新的单个数组项覆盖userDB.odds 数组。因此,现有关系将被删除,如FAQ 中所述:

    当您保存对象时,它会检查数据库中是否有任何类别与问题绑定 - 并且会分离所有类别。为什么?因为关系等于 [] 或其中的任何项目都将被视为已从其中删除了某些内容,因此没有其他方法可以检查对象是否已从实体中删除。

    因此,像这样保存对象会给您带来问题 - 它会删除所有先前设置的类别。

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2021-09-25
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多