From b72294749562b098543e2de6bbb8437d03f67d79 Mon Sep 17 00:00:00 2001 From: Yunus Emre Zengin Date: Sat, 5 Apr 2025 12:54:24 +0300 Subject: [PATCH] fix(db-postgres): count operation returns totalDocs:0 correctly when queried by a field of realtionship field --- packages/db-sqlite/src/countDistinct.ts | 2 +- .../drizzle/src/postgres/countDistinct.ts | 2 +- test/relationships/int.spec.ts | 35 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/db-sqlite/src/countDistinct.ts b/packages/db-sqlite/src/countDistinct.ts index de0af7a9953..b2212cdfab2 100644 --- a/packages/db-sqlite/src/countDistinct.ts +++ b/packages/db-sqlite/src/countDistinct.ts @@ -39,5 +39,5 @@ export const countDistinct: CountDistinct = async function countDistinct( // Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable. const countResult = await query - return Number(countResult[0]?.count) + return Number(countResult[0]?.count) || 0 } diff --git a/packages/drizzle/src/postgres/countDistinct.ts b/packages/drizzle/src/postgres/countDistinct.ts index 16c2f576c93..27883116d17 100644 --- a/packages/drizzle/src/postgres/countDistinct.ts +++ b/packages/drizzle/src/postgres/countDistinct.ts @@ -39,5 +39,5 @@ export const countDistinct: CountDistinct = async function countDistinct( // Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable. const countResult = await query - return Number(countResult[0].count) + return Number(countResult[0]?.count) || 0 } diff --git a/test/relationships/int.spec.ts b/test/relationships/int.spec.ts index 3694df14f57..4b6d4e462af 100644 --- a/test/relationships/int.spec.ts +++ b/test/relationships/int.spec.ts @@ -268,6 +268,41 @@ describe('Relationships', () => { expect(query.totalDocs).toEqual(2) }) + it('should count documents correctly when queried by a relationship field', async () => { + const user = ( + await payload.find({ + collection: 'users', + }) + ).docs[0]! + + for (let i = 0; i < 8; i++) { + await payload.create({ + collection: 'movieReviews', + data: { + movieReviewer: user.id, + visibility: 'public', + }, + }) + } + + const { totalDocs: countReviewedByUser } = await payload.count({ + collection: 'movieReviews', + where: { + 'movieReviewer.email': { equals: user.email }, + }, + }) + + expect(countReviewedByUser).toEqual(8) + + const { totalDocs: countReviewedByNonExistent } = await payload.count({ + collection: 'movieReviews', + where: { + 'movieReviewer.email': { equals: 'nonExistent@usermail.com' }, + }, + }) + expect(countReviewedByNonExistent).toEqual(0) + }) + // https://github.com/payloadcms/payload/issues/4240 it('should allow querying by relationship id field', async () => { /**