Skip to content

fix(db-postgres): count operation returns totalDocs:0 correctly when queried by a field of realtionship field #12008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/db-sqlite/src/countDistinct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion packages/drizzle/src/postgres/countDistinct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
35 changes: 35 additions & 0 deletions test/relationships/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '[email protected]' },
},
})
expect(countReviewedByNonExistent).toEqual(0)
})

// https://github.com/payloadcms/payload/issues/4240
it('should allow querying by relationship id field', async () => {
/**
Expand Down