© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•16mo ago•
1 reply
Eddy Vinck

aggregation core queries in extras?

Saw this in the docs. How do I do a count() here? Does it require a separate query or can I still combine it into one request?

the
core queries
core queries
links to https://orm.drizzle.team/docs/select

Can I use this in the
extras
extras
?

This is what I would like to add to the query:

const fineTunedModelsTotalThisMonthQuery = db
  .select({ count: count() })
  .from(fineTunedModels)
  .where(
    and(
      eq(fineTunedModels.userId, userId),
      sql`${fineTunedModels.createdAt} >= date_trunc('month', now()) AND ${fineTunedModels.createdAt} < date_trunc('month', now()) + interval '1 month')`,
    ),
  );
const fineTunedModelsTotalQuery = db
  .select({ fineTunedModelsTotal: count() })
  .from(fineTunedModels)
  .where(eq(fineTunedModels.userId, userId));

const dbUser = await db.query.users.findFirst({
  with: {
    fineTunedModels: {
      extras: {
        totalThisMonth: fineTunedModelsTotalThisMonthQuery,
        total: fineTunedModelsTotalQuery,
      }
    },      
  },
  where: (user, { eq }) => {
    return eq(user.id, userId);
  },
});
const fineTunedModelsTotalThisMonthQuery = db
  .select({ count: count() })
  .from(fineTunedModels)
  .where(
    and(
      eq(fineTunedModels.userId, userId),
      sql`${fineTunedModels.createdAt} >= date_trunc('month', now()) AND ${fineTunedModels.createdAt} < date_trunc('month', now()) + interval '1 month')`,
    ),
  );
const fineTunedModelsTotalQuery = db
  .select({ fineTunedModelsTotal: count() })
  .from(fineTunedModels)
  .where(eq(fineTunedModels.userId, userId));

const dbUser = await db.query.users.findFirst({
  with: {
    fineTunedModels: {
      extras: {
        totalThisMonth: fineTunedModelsTotalThisMonthQuery,
        total: fineTunedModelsTotalQuery,
      }
    },      
  },
  where: (user, { eq }) => {
    return eq(user.id, userId);
  },
});
image.png
Drizzle ORM - Select
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Lateral Left Joins in Drizzle Core Queries
Drizzle TeamDTDrizzle Team / help
3y ago
Using extras in where
Drizzle TeamDTDrizzle Team / help
2y ago
Error using relational queries but not with core queries
Drizzle TeamDTDrizzle Team / help
3y ago
Bug: Count in Extras (Relational)
Drizzle TeamDTDrizzle Team / help
9mo ago