簡體   English   中英

如何將字符串數組轉換為 Prisma Select 語句

[英]How to Convert String Array into Prisma Select Statement

我想動態 select Prisma 列,我從客戶端得到這個:

['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc']

我想把它改成這樣:

{id: true, createdAt: true, updatedAt: true, Order: {select: {id: true, Item: {select: {id: true, desc: true}}}}

這樣我就可以在 Prisma 查詢中使用它,例如:

prisma.sales.findMany({where: {id: {_eq: 1}}, select: {id: true, createdAt: true, updatedAt: true, Order: {select: {id: true, Item: {select: {id: true, desc: true}}}}}})

您可以構建一個簡單的遞歸 function 來構建 object 並填充嵌套屬性:

 const objPaths = ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc']; function buildObject(paths) { const result = {}; for (const path of paths) { const pathParts = path.split("."); if (pathParts.length > 1) { populateNested(result, pathParts, 0); } else { result[path] = true; } } return result; } function populateNested(parent, paths, currPathIndex) { if (currPathIndex === paths.length - 1) { parent[paths[currPathIndex]] = true; } else { let currObj = {select: {}}; if (parent[paths[currPathIndex]]) { currObj = parent[paths[currPathIndex]]; } parent[paths[currPathIndex]] = currObj; populateNested(currObj.select, paths, currPathIndex + 1); } } console.log(JSON.stringify(buildObject(objPaths), null, 2));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM