typeorm icon indicating copy to clipboard operation
typeorm copied to clipboard

TypeORM RelationCount alternative

Open daniel-dia opened this issue 4 years ago • 6 comments

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. ?

daniel-dia avatar Oct 16 '19 20:10 daniel-dia

Did you ever find a solution?

kevinelliott avatar Feb 06 '20 19:02 kevinelliott

Would love an example on how to count relations using query builder! @pleerock

Jaxkr avatar Mar 04 '20 17:03 Jaxkr

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
    }
}

nbouliol avatar Jul 08 '20 21:07 nbouliol

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

j1i-ian avatar Jul 26 '20 16:07 j1i-ian

@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!

kjr247 avatar Dec 23 '20 02:12 kjr247

@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 🤯

alielkhateeb avatar Sep 07 '22 15:09 alielkhateeb