Get a Quote Right Now

Edit Template

CTE in TypeOrm

QueryBuilder instances support common table expressions , if minimal supported version of your database supports them. Common table expressions aren’t supported for Oracle yet.

const users = await connection.getRepository(User)
    .createQueryBuilder('user')
    .select("user.id", 'id')
    .addCommonTableExpression(`
      SELECT "userId" FROM "post"
    `, 'post_users_ids')
    .where(`user.id IN (SELECT "userId" FROM 'post_users_ids')`)
    .getMany();

This code is using TypeORM's QueryBuilder to fetch a list of users based on certain conditions. Let's go through each part of the code to understand its functionality:

connection.getRepository(User):

This retrieves the repository for the User entity. The User entity is likely defined in your application and represents a table in your database.
createQueryBuilder('user'):

This starts building a query for the User entity, using the alias 'user'.
.select("user.id", 'id'):

This specifies that you want to select the id column from the user table and alias it as 'id'.
.addCommonTableExpression(...):

This method is used to add a common table expression (CTE) to the query. A CTE is a temporary result set that you can reference within your main query.
In this case, a CTE is being added that selects the "userId" column from the "post" table.
The second argument 'post_users_ids' is an alias for the CTE that can be used in the rest of the query.
.where(user.id IN (SELECT "userId" FROM 'post_users_ids')):

This sets a WHERE condition for the main query. It checks if the id of the user is present in the list of "userId" values obtained from the CTE.
The IN operator is used to compare the id with the list of "userId" values.
.getMany():

This executes the query and fetches all the rows that match the conditions you've set. In this case, it retrieves an array of user entities that meet the criteria.
In summary, this code fetches a list of users from the database based on whether their id values are found in the "userId" column of the "post" table. It uses a common table expression to extract the "userId" values from the "post" table and then checks for a match using the IN operator in the WHERE condition. The result is an array of user entities that meet the specified criteria.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *