$count with relation api returning wrong values ( 2 instead of 0)

async function findProjectById(id: number) {
return await db.query.projects.findFirst({
where: eq(projects.id, id),
with: {
...
matches:true
},
extras: {
matchesCount: db
.$count(matches, eq(matches.projectId, projects.id))
.as("matchesCount"),
},
});
async function findProjectById(id: number) {
return await db.query.projects.findFirst({
where: eq(projects.id, id),
with: {
...
matches:true
},
extras: {
matchesCount: db
.$count(matches, eq(matches.projectId, projects.id))
.as("matchesCount"),
},
});
output: project 1 >> { id: 1, matches: [], matchesCount: '2' } expected project 1 >> { id: 1, matches: [], matchesCount: '0' }
1 Reply
uber
uberOP3w ago
the following works :
extras: {
matchesCount: sql`${db
.select({ count: count() })
.from(matches)
.where(eq(matches.projectId, projects.id))}`
.mapWith(Number)
.as("matchesCount"),
},
extras: {
matchesCount: sql`${db
.select({ count: count() })
.from(matches)
.where(eq(matches.projectId, projects.id))}`
.mapWith(Number)
.as("matchesCount"),
},
Also mapWith doesnt work i get : project 1 >> { id: 1, matches: [], matchesCount: '0' } @here

Did you find this page helpful?