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: db.$count(schema.users).as('posts_count'),
  },
});