Question: How to reuse a query / share where clauses?
See original GitHub issueIssue type: [x] question
Database system/driver:
[x] postgres
TypeORM version:
[x] latest
Hello!
I’m trying to run a few queries which share common where clauses/joins, I thought i could do something like this:
const query = Booking.createQueryBuilder("booking")
.where("booking.spaceId = :spaceId", { spaceId: space.id })
.andWhere("booking.admin = FALSE")
.andWhere("booking.date BETWEEN :begin AND :end", {
begin,
end,
})
const totalBookings = await query.getCount()
const totalCancelled = await query
.andWhere("booking.cancelled = TRUE")
.getCount()
const totalTrial = await query
.andWhere("booking.trial = TRUE")
.getCount()
But it seems that by the time it runs the totalTrial query it’s combined all the previous queries, i assume this is because i’m “mutating” the original query. I’ve tried using getQuery()/getSql()/subQuery(), but i dont really know how to use those and cant find anything in the docs about sharing queries. So my question is: what is the best way to do what im trying to do?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:8 (2 by maintainers)
Top Results From Across the Web
How to reuse where clauses in Linq To Sql queries
You need to build an expression instead of a function: Expression<Func<Record, bool>> filter = record => record.Field1.ToLower().
Read more >Field Filters: create smart filter widgets for SQL questions
Learn how to use Metabase Field Filters in SQL queries to build filter widgets. ... You simply supply a Field Filter to a...
Read more >Best Practices to Write SQL Queries: How To Structure Your ...
1. Remove multiple nested queries ... Even without understanding exactly what the code is doing, we can see that it has several nested...
Read more >Reuse a complex non-deterministic expression in SELECT ...
Using the name score_points in the WHERE clause gives an error. Is there an efficient way to have the results of my expression...
Read more >How to write SQL Queries using WITH Clause - YouTube
SQL WITH Clause | How to write SQL Queries using WITH Clause | SQL CTE (Common Table Expression)In this video, we shall understand...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This is not currently possible - your best bet would be to create a helper function that creates a new query builder with your desired extra options.
I’m doin’ my best! There’s about 1800 left to get through.
And for other questions, please check out the community slack or check TypeORM’s documentation page on other support avenues - cheers!