繁体   English   中英

如何在TypeORM中一次添加多个关系

[英]How to add multiple relations one at a time in TypeORM

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

用户实体:

 @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); 这不起作用。

任何帮助,将不胜感激!

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM