Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typeorm

nestjs

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

like image 286
Pankaj Kumar Avatar asked Jul 29 '20 16:07

Pankaj Kumar


People also ask

What is Createquerybuilder?

QueryBuilder is one of the most powerful features of TypeORM - it allows you to build SQL queries using elegant and convenient syntax, execute them and get automatically transformed entities. Simple example of QueryBuilder : const firstUser = await dataSource. . getRepository(User)

How do I use QueryBuilder TypeORM?

In many cases, the query to find different entity object will be same except values. For example, the query to find different student is same except the Student ID data. In this case, we can use parameter for Student ID and then change the parameter to get the different student objects.

What is Type ORM?

TypeORM is a TypeScript ORM (object-relational mapper) library that makes it easy to link your TypeScript application up to a relational database database. TypeORM supports MySQL, SQlite, Postgres, MS SQL Server, and a host of other traditional options.

What is Type ORM in node JS?

TypeORM is an Object Relational Mapper library running in node. js and written in TypeScript. TypeScript is an improvement to JavaScript with optional typing. TypeScript is a compiled language. It is not interpreted at run-time.


1 Answers

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

like image 191
Ming-Kai Ko Avatar answered Oct 10 '22 02:10

Ming-Kai Ko