简体   繁体   中英

For Prisma Client join queries is it possible to move deeply nested fields to top level of result?

Does Prisma have the ability to move nested fields from another table join to the top level of the result, like a flattened view? I want to put the result JSON into a frontend table without digging through nested objects and building another object.

For example I want to replicate this behavior where I can pick and choose the columns from different tables (columns from User, and School). Currently I use a raw query with a similar SQL, however I wonder if it's possible with 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| student1@email.com | mount high

I want JSON that looks like this:
{
        "id": "1",
        "email": "student1@email.com",
        "school_name": "mount high",
}

If I did this in Prisma, I would need to go into several levels of nested objects to get the same column name on another table for eg user[user_school][schoo][school_name] . This requires extra work to loop through all my results, extract from the nested object, and build another object. This example isn't too bad, but I have more joins and deeply nested objects for my actual problem (lots of association/lookup tables). I've experimented with the select and include for my joins, but they are structured with the nested JSON.

users = await prisma.user.findMany({
        include: {
          user_school: {
            include: {
              school: true,
            },
          },
        },
{
        "id": "1",
        "email": "student1@email.com",
        "user_school": [
            {
                "id": 1,
                "user_id": "1",
                "school_id": "1",
                "school": {
                    "id": 1,
                    "school_name": "mountain high",
                }
            }
        ],
}

It's not possible to flatten out the results as of now.

The only way to achieve this would be by using rawQuery as you mentioned.

However, there is an existing Feature Request which discusses Flattening out the results by providing an option of flatten:true . If you could mention your use case there and add a comment it would help Prisma's Product and engineering team in prioritising it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM