Is it feasible to rearrange deeply nested fields to the top level of the result when using join queries in Prisma Client?

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"
                }
            }
        ]
}

Answer №1

Unfortunately, at this time, flattening out the results is not a supported feature.

The only available method to accomplish this task is by utilizing the rawQuery function as you previously mentioned.

There is an open Feature Request addressing this issue and proposing the addition of an option for flatten:true. If you could share your specific use case in that thread and leave a comment, it would greatly assist Prisma's Product and engineering team in evaluating its priority.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Webpack's dynamic dependency loading feature

I have a folder containing various files: /web/public/js/core Within my core folder, I have modules such as: modules, helper, config, styl, core.js, base.js, service.js. When using webpack for building, I utilize dynamic require in my service.js file. F ...

Encountering the issue of receiving an error message that says "emitted value instead of an instance of error while compiling template" when trying to set

Trying to set up a Vue table with the help of a Vue table plugin in my application through node module is proving to be challenging. An error keeps popping up when I try to use all Vue table components. I installed all Vue table plugins using npm and impor ...

Vue 3 sub-component failing to reflect changes in parent component data

I'm running into an issue with Vue 3. Whenever I update the data used to generate content in a subcomponent, the subcomponent fails to reactively update. I've been using the setup() function for the subcomponent, and I thought that props in Vue 3 ...

Displaying JSON information in a Swift 4 table view

I am currently working with JSON data and have successfully parsed the first part which includes navigation and names. Now, my task is to parse the 'children' array and display it in a table view. { "nav": [ { "name": "Home", ...

Transforming JSON data into a more organized and visually appealing format by utilizing Jackson for Pretty

The JSON string provided is as follows: {"attributes":[{"nm":"ACCOUNT","lv":[{"v":{"Id":null,"State":null},"vt":"java.util.Map","cn":1}],"vt":"java.util.Map","status":"SUCCESS","lmd":13585},{"nm":"PROFILE","lv":[{"v":{"Party":null,"Ads":null},"vt":"java.u ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

In search of a VueJS Getter that specifically retrieves the values of the final JSON property and displays them as an array

I am currently using a Django REST API to transmit data to a VueJS front-end for display purposes. My goal is to showcase daily counts through a ChartJS graph. import { HorizontalBar } from '../BaseCharts' export default { extends: Horizontal ...

Creating a TeeChart for HTML5 that combines both stacked and normal series can be done by following these steps

Hey there! I'm currently utilizing TeeChart for HTML5 and I'm wondering how to create a chart with both stacked and normal series. Specifically, I need two series to be stacked and a third one to remain unstacked (normal). I attempted to utilize ...

Angular - Dynamically change the height of an input element based on its content's length

I'm looking to automatically adjust the height of my input text based on its content. I have a solution that works when the user is actively typing, triggering the (input) event and calling my adjustHeight function to update the input element's h ...

Tips for concealing an entire row of a table with Jquery

I am currently working on a system that involves a table with anchor tags named original and copy in each row. By clicking on these anchor tags, we are able to update the database whether the item is an original or a copy using ajax. However, I am facing a ...

Issue: A unique constraint has been violated while attempting to create a new field with Prisma in a Node.js application

Encountering a challenge in building a field using Prisma within a Node.js application. The Field model is defined as follows: model Field { id String @id @default(uuid()) label String type FieldType // ...

Animating CSS styles in Vue.js based on JavaScript triggers

Within my Vue.js application, I've implemented a login form that I'd like to shake whenever a login attempt fails. Though I have achieved the desired shaking effect, I'm not completely satisfied with my current solution. Here's a simpl ...

Why did my datatable append HTML only to get suddenly refreshed?

Having trouble figuring out why my code isn't working as expected. I believe the logic is correct, but for some reason the custom HTML doesn't persist after the second click. The goal is to display my custom HTML after a new tr element is added. ...

Show the contents of a JSON file using Vue

I have a JSON file containing some data that needs to be fetched and displayed in a component. In the actions of my Vuex store, I've implemented: async getTodos (context) { const todos = [] const response = await fetch('../../data/todos.jso ...

Tips for efficiently compacting JSON data within a Struct in Golang

package questionnaire import ( "encoding/json" ) type Items []Item type CreateData struct { Items []Item } type Item struct { Id enter code herestring `json:"id" required:"true"` CompCd string `json:"compCd" required ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...

What is the reason for the incompatibility between Bootstrap and Vanilla JavaScript?

Why does my slideshow crash when I use Bootstrap with vanilla JavaScript? It seems like there is a timeout or something... I'm not sure why this is happening. When I remove Bootstrap, the slideshow works fine. Here is my code: I attempted to remove ...

Solution for displaying table cells in IE 7 and lower using Javascript

Lately, the community has come up with some amazing tools to push early versions of IE beyond their intended capabilities. For example, using multi-column CSS selectors. However, I've been struggling to find a JavaScript that can be loaded conditional ...

Adjust the text area to automatically expand or shrink based on the text it contains

Is there a way to automatically adjust the size of a textarea based on its content? Here is the code I am currently using for this purpose: var element = document.getElementById(event.target.id); var content = $(this).val().trim(); if (content == "") { ...

React Sentry Error: Attempting to access properties of undefined object (reading 'componentStack')

Utilizing the ErrorBoundry component from Sentry in my react project has been a goal of mine. I aim to confine the errors reported to Sentry specifically for my React app, as it is deployed on multiple websites and I want to avoid picking up every JS error ...