Javascript 在TypeForm中,如何在实体上基于该实体的其他字段预先计算字段?
我想在我的用户实体上创建一个“评级”字段。 用户实体与评级实体有关系,在用户上有一个名为ratingsReceived的字段,该字段是分配给该用户的所有评级的一个急加载 我希望用户上的“评级”字段是所有评级值的平均计算值,这是评级实体上名为“评级值”的字段 所以本质上我希望这个计算是每个用户“评级”字段的值:Javascript 在TypeForm中,如何在实体上基于该实体的其他字段预先计算字段?,javascript,sql,typescript,sequelize.js,typeorm,Javascript,Sql,Typescript,Sequelize.js,Typeorm,我想在我的用户实体上创建一个“评级”字段。 用户实体与评级实体有关系,在用户上有一个名为ratingsReceived的字段,该字段是分配给该用户的所有评级的一个急加载 我希望用户上的“评级”字段是所有评级值的平均计算值,这是评级实体上名为“评级值”的字段 所以本质上我希望这个计算是每个用户“评级”字段的值: ratingsReceived.reduce((acc,curr)=>acc+curr.ratingValue,0)/ratingsReceived.length 有问题的字段是用户的“r
ratingsReceived.reduce((acc,curr)=>acc+curr.ratingValue,0)/ratingsReceived.length
有问题的字段是用户的“ratingsReceived”:
@OneToMany(
() => Rating,
rating => rating.ratingTo
)
ratingsReceived: Rating[];
以及评级上的“评级值”:
@Column('decimal')
@Min(0)
@Max(5)
ratingValue: number;
经过反复试验,我们成功地为这种情况创建了一个解决方案,如下所示:
// After load is called after the entity loads during find() and similar
// I placed this decorator on my User Entity
@AfterLoad()
calculateRating = async () => {
const result = await getRepository(Rating)
.createQueryBuilder('ratings')
.where('ratings."ratingToId" = :id', { id: this.id })
.getRawAndEntities();
const ratingsAboveZero = result?.entities?.filter(x => parseFloat(x.ratingValue));
const count = ratingsAboveZero.length;
if (count > 0) {
this.rating =
ratingsAboveZero.reduce((acc, curr) => {
return acc + parseFloat(curr.ratingValue);
}, 0) / count;
this.ratingCount = count;
} else {
this.rating = 0;
this.ratingCount = 0;
}
};