Drizzle 查询工具
$count
db.$count() 是 count(*) 的一个工具封装,它是一个非常灵活的操作符,既可以直接使用,也可以作为子查询使用,更多细节请查看我们的 GitHub 讨论。
const count = await db.$count(users);
// ^? number
const count = await db.$count(users, eq(users.name, "Dan")); // 与过滤条件配合使用select count(*) from `users`;
select count(*) from `users` where `users`.`name` = 'Dan';它在 子查询 中尤其有用:
const users = await db.select({
...users,
postsCount: db.$count(posts, eq(posts.authorId, users.id)),
}).from(users);与 关系查询 配合使用示例
const users = await db.query.users.findMany({
extras: {
postsCount: (t) => db.$count(posts, eq(posts.authorId, t.id)),
},
});