Include count of relations

How can I achieve the same this Prisma query does in Drizzle?
const result = await prisma.user.findUnique({
where: { id },
include: {
posts: {
select: {
_count: true
}
}
}
});
const result = await prisma.user.findUnique({
where: { id },
include: {
posts: {
select: {
_count: true
}
}
}
});
I'd like to include the number of posts the user has created in the result
2 Replies
Mykhailo
Mykhailo12mo ago
Hello, @AstroBear! You can do something like this:
const userId = 'TestUserId';

const response = await db
.select({
postsCount: count(posts.id),
})
.from(users)
.where(eq(users.id, userId))
.leftJoin(posts, eq(posts.authorId, userId));
const userId = 'TestUserId';

const response = await db
.select({
postsCount: count(posts.id),
})
.from(users)
.where(eq(users.id, userId))
.leftJoin(posts, eq(posts.authorId, userId));
AstroBear
AstroBearOP12mo ago
Nice, thank you!
Want results from more Discord servers?
Add your server