【问题标题】:How to Convert String Array into Prisma Select Statement如何将字符串数组转换为 Prisma Select 语句
【发布时间】:2022-01-20 04:20:24
【问题描述】:

我想动态选择 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}}}}}})

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 它只适用于两级
  • edit您的问题并在那里添加代码。

标签: javascript node.js typescript web-deployment prisma


【解决方案1】:

您可以构建一个简单的递归函数来构建对象并填充嵌套属性:

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-26
    • 2014-04-03
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多