Skip to content

Commit 1510e12

Browse files
authored
fix(db-postgres): joins count with hasMany relationships (#14008)
Fixes #13950
1 parent 267ea9e commit 1510e12

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

packages/drizzle/src/find/traverseFields.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import type { SQL } from 'drizzle-orm'
21
import type { LibSQLDatabase } from 'drizzle-orm/libsql'
32
import type { SQLiteSelect, SQLiteSelectBase } from 'drizzle-orm/sqlite-core'
43

@@ -730,17 +729,24 @@ export const traverseFields = ({
730729
const subQuery = query.as(subQueryAlias)
731730

732731
if (shouldCount) {
732+
let countSubquery: SQLiteSelect = db
733+
.select(selectFields as any)
734+
735+
.from(newAliasTable)
736+
.where(subQueryWhere)
737+
.$dynamic()
738+
739+
joins.forEach(({ type, condition, table }) => {
740+
countSubquery = countSubquery[type ?? 'leftJoin'](table, condition)
741+
})
742+
733743
currentArgs.extras[`${columnName}_count`] = sql`${db
734744
.select({
735745
count: count(),
736746
})
737-
.from(
738-
sql`${db
739-
.select(selectFields as any)
740-
.from(newAliasTable)
741-
.where(subQueryWhere)
742-
.as(`${subQueryAlias}_count_subquery`)}`,
743-
)}`.as(`${subQueryAlias}_count`)
747+
.from(sql`${countSubquery.as(`${subQueryAlias}_count_subquery`)}`)}`.as(
748+
`${subQueryAlias}_count`,
749+
)
744750
}
745751

746752
currentArgs.extras[columnName] = sql`${db

test/joins/int.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,18 @@ describe('Joins Field', () => {
215215
expect(categoryWithPosts.group.relatedPosts?.totalDocs).toBe(15)
216216
})
217217

218+
it('should count hasMany relationship joins', async () => {
219+
const res = await payload.findByID({
220+
id: category.id,
221+
collection: categoriesSlug,
222+
joins: {
223+
hasManyPosts: { limit: 1, count: true },
224+
},
225+
})
226+
227+
expect(res.hasManyPosts?.totalDocs).toBe(15)
228+
})
229+
218230
it('should populate relationships in joins', async () => {
219231
const { docs } = await payload.find({
220232
limit: 1,

0 commit comments

Comments
 (0)