Is it possible for Prisma to flatten nested fields from a table join and move them to the top level of the result JSON? I want to simplify the structure for displaying data in a frontend table without dealing with nested objects.
For instance, I would like to achieve the same result as the following SQL query by selecting columns from multiple tables (User and School) using only the Prisma API:
SELECT
u.id
, u.email
, s.school_name
FROM "User" AS u
JOIN "UserSchool" AS us ON us.user_id = u.id
JOIN "School" AS s ON s.id = us.school_id
id | email | school_name
123| <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c0f0809181912084d3c19111d1510521f1311">[email protected]</a> | mount high
The desired JSON output is:
{
"id": "1",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0172757465646f753041646c60686d2f626e6c">[email protected]</a>",
"school_name": "mount high"
}
If attempted with Prisma, accessing the same column name on another table involves navigating through several levels of nested objects such as
user[user_school][schoo][school_name]
. This entails additional effort to iterate through results, extract from nested objects, and construct a new object. While the provided example may not be overly complex, my actual issue involves numerous joins and deeply nested objects (involving many association/lookup tables). I have tried utilizing the select
and include
features for my joins, but they produce structured nested JSON outputs.
users = await prisma.user.findMany({
include: {
user_school: {
include: {
school: true,
},
},
},
{
"id": "1",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0271767766676c763342676f636b6e2c616d6f">[email protected]</a>",
"user_school": [
{
"id": 1,
"user_id": "1",
"school_id": "1",
"school": {
"id": 1,
"school_name": "mountain high"
}
}
]
}