question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

leftJoinAndSelect with subQuery example?

See original GitHub issue

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] sqlite [ ] sqljs [ ] react-native

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

Hi, I have the following query:

let query = connection
  .createQueryBuilder(Chat, "chat")
  .leftJoin('chat.listingMembers', 'listingMembers')
  .where('listingMembers.id = :id', {id: currentUser.id})
  .leftJoinAndSelect('chat.messages', 'messages')
  .orderBy({
    "messages.createdAt": {order: "DESC", nulls: "NULLS LAST"},
    "chat.id": "DESC",
  });

I would like to filter the messages, with the following:

  .innerJoin('messages.holders', 'holders', 'holders.id = :userId', {userId: currentUser.id})

Unfortunately if I simply append the previous method it will filter out all the chats without messages, while I simply want to filter out all the messages which do not match the criteria.

I think that in order to obtain the desired result I will have to use leftJoinAndSelect with a subQuery, then do the innerJoin inside the subQuery. Unfortunately I didn’t find any usage example with subQuery and leftJoinAndSelect, so I didn’t manage to get it working. Can you please tell me the right syntax in order to achieve that?

Thanks

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:8
  • Comments:12 (7 by maintainers)

github_iconTop GitHub Comments

7reactions
darkbasiccommented, May 14, 2018

I saw those examples, but there is none with leftJoinAndSelect and I’m uncertain how to use it…

let query = connection
  .createQueryBuilder(Chat, "chat")
  .leftJoin('chat.listingMembers', 'listingMembers')
  .where('listingMembers.id = :id', {id: currentUser.id})
  .leftJoinAndSelect(subQuery => {
    return subQuery
      .from(Message, "message")
      .innerJoin('message.chat', 'chat', 'chat.id = :chatId', {chatId: <???>})
      .innerJoin('message.holders', 'holders', 'holders.id = :userId', {userId: currentUser.id})
      .orderBy({"message.createdAt": "DESC"});
  }, "messages")
  .orderBy({
    "messages.createdAt": {order: "DESC", nulls: "NULLS LAST"},
    "chat.id": "DESC",
  });

In the previous code, how do I do the JOIN part between chat and message?

I thought about something like this, but it’s not working:

.leftJoinAndSelect(subQuery => {
  return subQuery
    .from(Message, "message")
    .innerJoinAndSelect('message.chat', 'chat')
    .innerJoin('message.holders', 'holders', 'holders.id = :userId', {userId: currentUser.id})
    .orderBy({"message.createdAt": "DESC"});
}, "messages", 'chat.id = message.chat.id')

Regarding your last suggestion:

From what I got you need to do: .where('holders.id = :userId OR holders IS NULL')

This is not going to work. What I need to do is an innerJoin between messages and holders and then a leftJoin beftween messages and chats.

If I do something like

.leftJoinAndSelect('chat.messages', 'messages')
.innerJoin('messages.holders', 'holders', 'holders.id = :userId', {userId: currentUser.id})

it will discard all the chats that contain no messages: it’s basically doing an innerJoin between chats and holders, while I want to do an innerJoin between messages and holders and then a leftJoin between messages and chats.

3reactions
Nieliocommented, Aug 11, 2022

Since i was not happy with getRawMany, because you can not parse that data to TypeORM Entities. I tried to solve this problem on my own.

AND HERE IT IS!

You can use the subquery in the contition param on the joins functions.

 const subQuery = this.connection
      .createQueryBuilder(UserViews, 'views')
      // where and other things also possible
      .orderBy('views.createdAt', 'DESC')
      .limit(1);

    this.connection
      .createQueryBuilder(User, 'user')
      .andWhereInIds(id)
      .leftJoinAndSelect(
        'user.userViews',
        'views',
        `views.id IN (${subQuery.select('id').getQuery()})`,
      )
      .getOne();

I did not testet it with your model, but for my stuff this works very well. I hope someone finds this helpfull 😃

It should also be possible to nest multiple subqueries and do some komplex filtering stuff. Especially good for nested access control handling.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Is it possible to use subquery in leftJoinAndSelect in TypeORM
In docs it's said that "Subqueries are supported in FROM, WHERE and JOIN expressions." but no example is provided. So, i have no...
Read more >
Is it possible to use subquery in leftJoinAndSelect in TypeORM
In docs it's said that "Subqueries are supported in FROM, WHERE and JOIN expressions." but no example is provided. So, i have no...
Read more >
TypeORM - Query Builder with Subquery - DEV Community ‍ ‍
The article demonstrates how complex subquery should be created with TypeORM in Node.js, TypeScript. Tagged with node, sql, typescript, ...
Read more >
Select using Query Builder - typeorm - GitBook
​Using subqueries​. ​Hidden Columns​ ... Simple example of QueryBuilder : ... As you can see leftJoinAndSelect automatically loaded all of Timber's photos.
Read more >
TypeORM Query Builder Wrapper - Medium
and import it somewhere in the global place of your app (for example in app.ts ): ... It has 1 argument that has...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found