P
Prisma•4mo ago
Wiznet

find first on relation queries

Hey all, how do I run a find first but only on the relations of a query? For example I want to get all the users in my db, but only return the first result for their relation. Using the posts example from the docs, I would want to get all the users and only one post.
1 Reply
RaphaelEtim
RaphaelEtim•3mo ago
Hi @Wiznet 👋 To achieve this, you can use the findMany method to get all users and include only the first related post for each user. You can use the include option with take to limit the number of posts returned for each user.
const usersWithSinglePost = await prisma.user.findMany({
include: {
posts: {
take: 1, // Limit the number of posts to 1
orderBy: {
date: 'desc', // Optionally, sort the posts by date or any other field
},
},
},
});

console.log(usersWithSinglePost);
const usersWithSinglePost = await prisma.user.findMany({
include: {
posts: {
take: 1, // Limit the number of posts to 1
orderBy: {
date: 'desc', // Optionally, sort the posts by date or any other field
},
},
},
});

console.log(usersWithSinglePost);
Want results from more Discord servers?
Add your server