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)),
},
});