typeorm
typeorm copied to clipboard
TypeORM RelationCount alternative
I'm working with TypeORM for a while into a project. We have an Entity that holds the followings properties
@RelationCount("sentences")
public sentencesCount?: number;
@OneToMany(() => Sentence, e => e.job)
public sentences?: Sentence[];
However I noticed that RelationCount
is depreciated
@RelationCount, deprecated Do not use this decorator, it may be removed in the future versions
I look for a substitution in TypeORM official readme but I found nothing but creating a custom QueryBuilder
with a native SQL SELECT COUNT(*)
statement.
In this project we use a lot of simple statement like myRepo.find()
. I rather not to replace all these simple calls for QueryBuilders
.
What should I use instead of @RelationCount
in our project?
Should I ignore this "depreciate" warning. ?
Did you ever find a solution?
Would love an example on how to count relations using query builder! @pleerock
Hey !
Not sure if it's the best way, but here's what I did
@Entity()
export class Post extends BaseEntity {
@PrimaryGeneratedColumn()
id: number
// other fields
@OneToMany((type) => Like, (like) => like.post)
likes: Like[]
likesCount: number
@AfterLoad()
async countLikes() {
const { count } = await Like.createQueryBuilder('like')
.where('like.post_id = :id', { id: this.id })
.select('COUNT(*)', 'count')
.getRawOne()
this.likesCount = count
}
}
You can use loadRelationCountAndMap instead of addSelect or RelationCount
like this
const loadedProduct = await repository.createQueryBuilder('statement')
.loadRelationCountAndMap('statement.sentencesCount', 'statement.sentences')
but I don't know how counting entity relations globally except using Typeorm Subscriber..
maybe you should refer this merge request : https://github.com/typeorm/typeorm/pull/4703
I think just use before somethinkg replace @RelationCount
@nbouliol That is super helpful! I'm not quite sure how it's supposed to be used, but very helpful! I see something strange where we can't use this value in any queries, but the value is populating!
@j1i-ian Do you know how can you allow typescript to see this statement.sentencesCount
on the const loadedProduct
?
I have similar code and when I try to use loadedProduct.sentencesCount
TS doesn't allow it since sentencesCount
is not part of the Statement entity 🤯