node.js - TYPEORM 过滤复杂 JSON 的数据
问题描述
我正在使用 typeorm 从 Postgres 检索以下数据,并且我想过滤这些数据:
[{ "corporateid": 1001, "customerdetail": [{ "customerid": 1,
"customertype": "CustType1", "products": [{ "productid": 1, "productcode":
9000, "currencydetailss": [{ "currencydetailsid": 1, "ratetype": "Cash",
"basecurrencyidFk": { "currencyid": 2, "currencyisocode": "IS0-9901",
"currencyname": "INR" }, "currencyrates": [{ "currencyratesid": 1,
"buyrate": 10.2, "sellrate":
11.2, "spotsell": 10.9 }, { "currencyratesid": 2, "buyrate": 98.2,
"sellrate": 99.2, "spotsell": 98.9 }, { "currencyratesid": 3, "buyrate":
11.2, "sellrate": 12.2, "spotsell": 11.9 }] }] }] }, { "customerid": 5,
"customertype": "CustType5", "products": [] }, { "customerid": 4,
"customertype": "CustType4", "products": [] }] }]
我尝试了什么:
const details = await conn .getRepository(corporate) .find({ where: [ { corporateid: "1001" ,'customerdetail.customerid'= 2} ] });
我还使用 where 条件尝试了 LeftJoin 和 InnerJoin:where: {corporateid: "1001",'customerdetail.customerid'= 2}
我尝试了多种其他方式。
关于如何通过传递可选参数从 JSON 中过滤数据的任何帮助?例如:我可能只是通过corporateid 或'corporateid 和customerid' 和许多类似的组合。
解决方案
所以我可以通过下面的代码来做到这一点,以防有人需要它:
let requestQueryParameters: { [key: string]: string } = {
"c2": 'CustType3',
"c3": '2'
};
let queryCriteriaPlaceHolders: { [key: string]: string } = {
"c2": "t2.c2= :c2",
"c3": "t4.c1= :c1",
};
const query = await conn
.getRepository(t1)
.createQueryBuilder("t1")
.leftJoinAndMapMany("t1.t2", t2, "t2", "t1.id = t2.id_fk")
.leftJoinAndMapMany("t2.t3", t3, "t3", "t3.id_fk=t2.id")
.leftJoinAndMapMany("t3.t4", t4, "t4", "t4.id_fk=t3.id")
.leftJoinAndMapOne('t4.c1', t5, 't5', 't4.c1=t5.c1')
.where("t1.id= :id", { id: 123 })
.andWhere("t4.c2= :c2", { c2: 456 });
Object.getOwnPropertyNames(requestQueryParameters).forEach(param => {
let paramValue = requestQueryParameters[param];
console.log("Key: " + param + " Value: " + paramValue);
let reqObjLiteral = {} as any;
reqObjLiteral[param] = paramValue
query.andWhere(queryCriteriaPlaceHolders[param], reqObjLiteral)
});
query.getMany();
推荐阅读
- java - 编写以枚举和字符串为参数的通用方法
- xml - 使用 XSLT1 有条件地显示来自 XML 的数据?
- project-reactor - 尝试管理多个 Flux/Mono,先开始其中一些,然后合并其中一些,然后有点迷失
- c++ - C++ - std::initializer_list 与 std::span
- r - 使用 gganimate 和 geom_sf 进行颜色填充的问题
- node.js - req.session 不在另一条路线上工作
- python - 爆炸后在熊猫中合并行
- python - 使用 python 的 Git 签出和扫描子目录
- typescript - 尝试将打字稿捆绑到单个文件会产生神秘的垃圾
- reactjs - 上传文件(图片/PDF)并使用 React 预览上传的图片/PDF