count() within query.findMany.with

I wonder if the new count() function can be used within query.model.findMany()? I didnt find a solution yet. Something like:
const items = await useDb().query.orders.findMany({
columns: {
id: true,
status: true,
},
with: {
products: {
columns: {
id: true,
},
},
},
extras: {
productsCount: count(products.id).as('products_count'),
},
});
const items = await useDb().query.orders.findMany({
columns: {
id: true,
status: true,
},
with: {
products: {
columns: {
id: true,
},
},
},
extras: {
productsCount: count(products.id).as('products_count'),
},
});
I saw this question came up a lot of times here on Discord but was never answered. I know an sql statement can be used but I would love to use count() without writing custom sql statements. Stackoverflow: https://stackoverflow.com/questions/79336230/how-to-use-count-within-query-findmany-in-drizzle-orm/79336237
1 Reply
Mario564
Mario5645w ago
@Mick count function is meant to be used in SQL-like query syntax. What you're looking for here is likely the $count method in the DB object:
const productsCount = db.$count(products).as('products_count')
const productsCount = db.$count(products).as('products_count')
You can read more about it here: https://orm.drizzle.team/docs/query-utils#count

Did you find this page helpful?