admin管理员组文章数量:1415420
I want to make a 'rating' field on my User Entity. The User Entity has a relationship to the Rating Entity, on User there is a field called ratingsReceived, which is an eager load of all Ratings assigned to that User.
I want the 'rating' field on User to be a mean calculation of all rating values which is a field on Rating Entity called 'ratingValue'.
So essentially I want this calculation to be the value of every User 'rating' field:
ratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length
The fields in question are 'ratingsReceived' on User:
@OneToMany(
() => Rating,
rating => rating.ratingTo
)
ratingsReceived: Rating[];
And 'ratingValue' on Rating:
@Column('decimal')
@Min(0)
@Max(5)
ratingValue: number;
I want to make a 'rating' field on my User Entity. The User Entity has a relationship to the Rating Entity, on User there is a field called ratingsReceived, which is an eager load of all Ratings assigned to that User.
I want the 'rating' field on User to be a mean calculation of all rating values which is a field on Rating Entity called 'ratingValue'.
So essentially I want this calculation to be the value of every User 'rating' field:
ratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length
The fields in question are 'ratingsReceived' on User:
@OneToMany(
() => Rating,
rating => rating.ratingTo
)
ratingsReceived: Rating[];
And 'ratingValue' on Rating:
@Column('decimal')
@Min(0)
@Max(5)
ratingValue: number;
Share
Improve this question
edited Apr 10, 2020 at 20:30
stephano
asked Mar 30, 2020 at 20:47
stephanostephano
1723 silver badges12 bronze badges
1
- typeorm.io/listeners-and-subscribers – Louis Huang Commented Jun 1, 2022 at 16:50
1 Answer
Reset to default 3After trial and error, managed to create a workaround for this like so:
// 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;
}
};
本文标签:
版权声明:本文标题:javascript - In TypeORM how do I have a pre-calculated field on an Entity based on other fields of that Entity? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745211845a2647934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论