Prisma DB is a versatile database that excels in handling m-n

In my database, I have implemented a structure with 3 tables: Member, Characters, and MemberCharacters. Each member can have multiple Characters, and each Character can be used by multiple Members. To handle this many-to-many relationship, I have utilized the MemberCharacters table, which stores the memberId and characterIds as foreign keys. Here is an overview of the table structure:

model Members {
  id String @unique @id @default(cuid())
  displayName String
  characters MemberCharacters[]
}
model Characters {
  id Int @id @default(autoincrement())
  name String
  pictureUrl String
  members MemberCharacters[]
}

model MemberCharacters {
  id String @id @default(cuid())
  memberId String
  Members Members @relation(fields: [memberId], references: [id])
  characterId Int
  Characters Characters @relation(fields: [characterId], references: [id])
}

Now, I am looking for a way to retrieve a JSON response containing all details about the Member along with a list of the Characters assigned to that Member.

In the Prisma documentation, I came across the option of using 'include'. Although this approach almost fulfills my requirements, it returns a JSON with all Member information and a list of MemberCharacter JSON objects. However, I specifically need the actual Character objects associated with those MemberCharacters in the list.

let result = await prisma.members.findMany({
            include: {
                characters: true
            }
        })
        console.log(result)

Current Result:

{
        id: '86548974659889456',
        displayName: 'DisplayName',
        characters: [ [Object], [Object], [Object], [Object], [Object] ]
}

Although the Prisma documentation suggests a different approach using just two tables, it is not suitable for my scenario as I cannot modify the data in Characters table. Therefore, I must stick with the original setup.

model Post {
  id         Int        @id @default(autoincrement())
  title      String
  categories Category[]
}

model Category {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}

Answer №1

To achieve this, you will need to utilize a nested include statement. Begin by including the MemberCharacters, followed by the actual Characters.

Given your existing schema, the query would appear as follows:

prisma.members.findMany({
  include: { characters: { include: { Characters: true } } },
});

Subsequently, you can flatten the result from such a query:

const members = await prisma.members.findMany({
  include: { characters: { include: { Characters: true } } },
});
const membersWithFlattenedCharacters = members.map((member) => ({
  ...member,
  flattenedCharacters: member.characters.map(
    (memberCharacter) => memberCharacter.Characters
  ),
}));

It seems that the current naming convention is somewhat confusing. I would recommend updating the schema as follows:

model Members {
  id               String @unique @id @default(cuid())
  displayName      String
  memberCharacters MemberCharacters[]
}

Subsequently, the adjusted query would be:

prisma.members.findMany({
  include: { memberCharacters: { include: { Characters: true } } },
});

By using singular names for the models, readability can be further improved...

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

What is the best way to incorporate data types into a React useReducer reducer function?

I originally had a useReducer function in pure react without TypeScript, but now I want to add types to it. Here is the useReducer reducer function in pure react without types: export const cartReducer = (state, action) => { switch (action.type) { ...

A mistake has occurred: Unhandled promise rejection TypeError: Unable to assign the property 'devices' to an undefined object in Ionic 4 with Angular

Within my MyDevicesPage class, I am attempting to manipulate the res object and then pass it to the updateDevicesToServer method of DataService for further actions. The code compiles without errors, but at runtime, an error is thrown: ERROR Error: Uncaught ...

Showing the child component as undefined in the view

Within my Angular application, I encountered an issue involving a parent component named DepotSelectionComponent and its child component SiteDetailsComponent. The problem arises when an event called moreDetails is emitted to the parent component, triggerin ...

Performing Jquery functions on several elements at once

Looking at the code snippet below, there are two buttons and an input in each container. The input calculates and adds up the number of clicks on the 2 buttons within the same container. However, it currently only works for the first container. How can thi ...

Tips for including a clickable button in an Angular textarea

I am looking for a solution to float a button to the top right corner of a text area in an Angular application. Below is my current code setup, but unfortunately, it does not achieve the desired result: <textarea matInput matInput rows="15" cols="40" ...

Verifying the URL to determine if it includes the specific string needed to modify the Jade theme in

I am currently exploring ways to check if a URL string is present in an express application, in order to initiate a theme change. At the moment, I have a basic router.get function: router.get('/', function(req, res, next) { res.render(' ...

What is the best way to apply three unique classes to multiple div elements using jQuery?

Utilizing jQuery to assign three different classes to my div elements with the same name. Here is the HTML: <div class="main-class"> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div& ...

Displaying nested arrays correctly

My latest endeavour involves constructing a data tree in Vue, utilizing components. Let's examine the provided data snippet: "data": [ { "id": 1, "name": "foo", "children": [ { "id": 2, "name": "bar", "children": [] } ...

Fade out and slide close a div using jQuery

I am creating a new website and incorporating jQuery for animation and simplified JavaScript implementation. My goal is to have a button that, when clicked, will close a div with a fading out and slide up effect. Can this be achieved? Thank you. ...

What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question! I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example ...

Utilize jQuery script on every single element

Is there a way to implement a jquery function on elements that are dynamically loaded via ajax? <span class="h">Test</span><br /><br /> <span class="h">Test</span><br /><br /> <span class="h">Test</ ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...

What is the reason behind appending a timestamp to the URL of a JavaScript resource?

$script.ready('jui',function() { $script('<?php base_path(); ?>js/partnerScripts.js?ts=1315442861','partners'); }); Can anyone explain why there is a fixed ts=timestamp at the end of the partnerScripts.js file name? I ...

pnpm may not be able to resolve dependencies

When I have my package.json file and install all dependencies with npm i, everything works fine. However, when I use pnpm i, I encounter an exception: TypeError: Cannot read property 'uid' of undefined. I don't actually use this library, so ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Using Mongoose and MongoDB to reference a different schema without using the default ObjectId reference

I have two different schemas in my current project. var carSchema = new mongoose.Schema({ id: { type: Number, unique: true, required: true }, make: { type: String, required: true }, model: { ...

importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public k ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

reduce the size of the image as the browser width decreases

Struggling with a webpage layout that features an image on the left and content area on the right, both with fixed widths. When reducing browser width, the image should not shrink but be cropped from the left side instead. Any solutions for this issue? ...

Tips for concealing content within table cells

I am facing an issue with my form that contains a table. When the user clicks on the radio button labeled "No", I want the content of the subsequent cells in that row to become visible. However, when they click on "Yes", the content should be hidden again. ...