Is there a way I can use Group By and Count with Type Orm Repository

Viewed 17090

I am new here recently joined and New in Type ORM My code that I am trying

FIRST QUERY: I would like to use this approach but not sure how I can group by with count on the column and then order by desc on that column

 const result = await this.jobViewsRepository.find({
        relations: ["jobs"],
        loadEagerRelations: true,  
        order: { id: "DESC" },
        skip: offset,
        take: limit,
    }
    );

I am trying if I can use this in my above query

SECOND QUERY: IT'S WORKING FOR ME PERFECTLY THE RESULT I AM LOOKING

    const res = await this.jobViewsRepository.createQueryBuilder('jobViews')           
    .addSelect("COUNT(jobViews.user_id) AS jobViews_total_count" )
    .leftJoinAndSelect(Jobs, "jobs", "jobs.id = jobViews.job_id")
    .where("jobs.user_id != :id", { id: user_id })        
    .groupBy("jobViews.job_id")**
    .orderBy('jobViews_total_count', 'DESC')**
    .limit(limit)
    .offset(offset)           
    .getRawMany();

Please if any can help me out in this will be really appreciated

Thanks

3 Answers

At least in the current version there is no way to do this feature (neither in the documentation nor in the web)

I believe you can use .query to write your own query

you use findAndCount to count the result size

   result = await this.jobViewsRepository.findAndCount({ ... })

the result = [data,count]

Related