Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJs Prisma double include property

I have 3 model schemas in my project:

  1. Vendors: id + name

  2. Items: id + name + vendorId

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  3. categories: id + name + ItemId

I need to create a prisma query schema that allows me to retrieve categories including details of the item and the vendor.

the prisma models:

model Vendor {
  id Int @id @default(autoincrement())
  name     String  @db.VarChar(255)
  Item Item[]
  @@map("Vendors")
}

model Item {
  id             Int       @id @default(autoincrement())
  name           String    @db.VarChar(255)
  vendor         Vendor    @relation(fields: [vendorId], references: [id])
  vendorId       Int
  Category Category[]
  @@map("Items")
}

model Category {
  id         Int      @id @default(autoincrement())
  name       String   @db.VarChar(255)
  item       Item     @relation(fields: [itemId], references: [id])
  itemId     Int

  @@map("Categories")
}   

The express endpoint is as follows:

router.get('', async (req, res) => {
    try {
        let items = await prisma.Category.findMany({
            include: {
               item: true
            },
        });

        res.status(200).json(items)
    } catch (error) {
        res.json(error.message);
    }

});

The code as is now, it will return a list of categories along with the items of each category, however, the item will include the vendorId instead of vendor details. What should I add to the code to get vendor details without the foreach loop

>Solution :

You can get the vendors along with items while fetching category through this query.

  let items = await prisma.category.findMany({
    include: {
      item: {
        include: {
          vendor: true,
        },
      },
    },
  });

  console.log(items);

Here’s the sample response for the query:

[
  {
    "id": 1,
    "name": "mobile",
    "itemId": 1,
    "item": {
      "id": 1,
      "name": "Iphone",
      "vendorId": 1,
      "vendor": {
        "id": 1,
        "name": "Apple Inc"
      }
    }
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading