[英]How to add multiple relations one at a time in TypeORM
So i've been struggling with this for some time now, i have this many to many realtionship in my codebase.所以我已经为此苦苦挣扎了一段时间,我的代码库中有很多对多方面的关系。 Between a User and Odds.
在用户和赔率之间。 I want the User to be able to add an Odds
我希望用户能够添加赔率
User Entity:用户实体:
@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;
}
}
Odds Entity:赔率实体:
@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[];
}
When i try to add a relation like this当我尝试添加这样的关系时
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();
}
In the associative table it does add the relation the first time, but if i add one more it overrides the first relation, i also tried userDB.odds.push(odds);在关联表中,它第一次添加了关系,但是如果我再添加一个它会覆盖第一个关系,我也尝试过 userDB.odds.push(odds); which doesnt work.
这不起作用。
Any help would be appreciated!任何帮助,将不胜感激!
The Problem is that your addOddsToUser
function overrides the userDB.odds
array with a new single array item each time.问题是您的
addOddsToUser
函数userDB.odds
用一个新的单个数组项覆盖userDB.odds
数组。 Thus existing relations will be deleted as mentioned in the FAQ :因此,现有关系将被删除,如常见问题中所述:
When you save the object it will check if there are any categories in the database bind to the question - and it will detach all of them.
当您保存对象时,它会检查数据库中是否有任何类别绑定到问题 - 它将分离所有类别。 Why?
为什么? Because relation equal to [] or any items inside it will be considered like something was removed from it, there is no other way to check if an object was removed from entity or not.
因为关系等于 [] 或其中的任何项目都将被视为从其中删除了某物,所以没有其他方法可以检查对象是否已从实体中删除。
Therefore, saving an object like this will bring you problems - it will remove all previously set categories.
因此,保存这样的对象会给您带来问题 - 它会删除所有先前设置的类别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.