Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

42
Vistas
NodeJs Prisma double include property

I have 3 model schemas in my project:

  1. Vendors: id + name

  2. Items: id + name + vendorId

  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

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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"
      }
    }
  }
]
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.