i want to create a deep nested menu dynamically with prisma ORM and get all menus with sub menus as a deeply nested json object this is my code and i already try a query to but the result is not what i want
this is my prismaSchema file
model Menu {
id Int @id @default(autoincrement())
title String
url String @default("#")
parentMenu Menu? @relation("parentSubCategory", fields: [parrentMenuId], references: [id])
subMenu Menu[] @relation("parentSubCategory")
parrentMenuId Int?
}
i want a query to get a json with deep nested menus and submenus like below
{
title:"menu1",
subMenu:[
{
title:"sub1"
subMenus:[
{
title:"sub3",
subMenus:[
{
title:"sub4"
}
]
}
]
}
]
}
I already try query below but the result is not wat i want
const result = await prisma.menu.findMany({
select: {
id: true,
title: true,
url: true,
subMenu: true,
},
});
result of my query is like this
"data": [
{
"id": 1,
"title": "sample",
"url": "#",
"subMenu": [
{
"id": 2,
"title": "digital",
"url": "#",
"parrentMenuId": 1
}
]
},
{
"id": 2,
"title": "digital",
"url": "#",
"subMenu": [
{
"id": 3,
"title": "pc & laptop",
"url": "#",
"parrentMenuId": 2
}
]
},
{
"id": 3,
"title": "pc & laptop",
"url": "#",
"subMenu": [
{
"id": 4,
"title": "pc",
"url": "#",
"parrentMenuId": 3
},
{
"id": 5,
"title": "laptop",
"url": "#",
"parrentMenuId": 3
}
]
},
{
"id": 4,
"title": "pc",
"url": "#",
"subMenu": [
{
"id": 6,
"title": "pc parts",
"url": "#",
"parrentMenuId": 4
}
]
},
{
"id": 5,
"title": "laptop",
"url": "#",
"subMenu": []
},
{
"id": 6,
"title": "pc parts",
"url": "#",
"subMenu": [
{
"id": 7,
"title": "ram and storage",
"url": "#",
"parrentMenuId": 6
}
]
},
can any one help me please?
Just add as many as sub-menus as present in that table in this nested structure.
const result = await prisma.menu.findMany({ select: { id: true, title: true, url: true, subMenu: { //first-sub menu id: true, title: true, url: true, subMenu: { //2nd one id: true, title: true, url: true, subMenu: { // 3rd one id: true, title: true, url: true, subMenu: true // Presumably the last sub menu } } }, }, });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.