I currently need to pull lots of nested data to format into a JavaScript object to send into a chart as the data, I am currently allowing ten nested deep, but there might be some cases when this just keeps on going.
I'm wondering if there is a better way to pull out data like this, I couldn't see anything in the docs, for pulling infinitely or dynamically nested data through the relationships.
This is what I currently have for example:
const [result] = await prisma.company.findMany({
where: {
users: {
some: {
email: {
contains: session.user.email,
},
},
},
},
select: {
name: true,
users: true,
id: true,
profiles: {
select: {
id: true,
name: true,
image: true,
category: {
select: { name: true },
},
children: {
select: {
id: true,
name: true,
image: true,
category: {
select: { name: true },
},
children: {
select: {
id: true,
name: true,
image: true,
category: {
select: { name: true },
},
children: {
select: {
id: true,
name: true,
image: true,
category: {
select: { name: true },
},
children: {
select: {
id: true,
name: true,
image: true,
category: {
select: { name: true },
},
children: {
select: {
id: true,
name: true,
image: true,
category: {
select: { name: true },
},
},
},
},
},
},
},
},
},
},
},
},
},
},
});
Have you considered using the include
statement instead of select
? It automatically fetches all non-relation fields, so you just have to manually specify the relation fields. The nested reads section in the prisma docs also contains a lot of examples for this.
In general, if you don't need granular control over which fields of the model get returned from the query, include
is the way to go.
Please check out my answer to a very similar question. I think you might find that solution relevant to your use-case.