leftJoinAndSelect with subQuery example?
See original GitHub issueIssue 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:
- Created 5 years ago
- Reactions:8
- Comments:12 (7 by maintainers)
I saw those examples, but there is none with
leftJoinAndSelect
and I’m uncertain how to use it…In the previous code, how do I do the
JOIN
part betweenchat
andmessage
?I thought about something like this, but it’s not working:
Regarding your last suggestion:
This is not going to work. What I need to do is an
innerJoin
betweenmessages
andholders
and then aleftJoin
beftweenmessages
andchats
.If I do something like
it will discard all the chats that contain no messages: it’s basically doing an
innerJoin
betweenchats
andholders
, while I want to do aninnerJoin
betweenmessages
andholders
and then aleftJoin
betweenmessages
andchats
.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.
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.