I have 3 model schemas in my project:
Vendors: id name
Items: id name vendorId
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
CodePudding user response:
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"
}
}
}
]