【发布时间】:2021-07-21 05:33:34
【问题描述】:
我将 objection.js 和 knex.js 用于我的 RESTful API。
在我的数据库中,我有三个表:products、characteristics 和 product_characteristics(使用名为“值”的额外列连接表)。
所以我要做的是获取所有具有相应特征值的产品。
在 GET 请求中,我接受 characteristics 查询参数并对其进行解析以获取我需要用来过滤我的产品的特征数组。
解析特征数组:
[{
characteristicId: number,
value: string
}, ...]
“产品”表字段:
[id, title, price, discount]
'特征的表格字段:
[id, name]
'product_characteristics' 连接表字段:
[productId, characteristicId, value]
目前我使用反对的queryBuilder 和withGraphFetch 方法以及page 和limit 方法获取所有产品:
const query: any = ProductModel.query()
.page(page - 1, limit)
.orderBy(sortBy, order)
.withGraphFetched({
category: true,
images: true,
characteristics: true,
});
const result = await query;
return {
products: result.results,
total: result.total,
};
Objection.js 提供了withGraphJoined 方法,该方法可以访问queryBuilder 中的相关实体,以便根据关系过滤parentModel,但不支持@987654337 @ 和 limit 方法。
因此,一种可能的解决方案是使用 knex.raw() 方法执行原始 SQL 查询。但是我花了一天时间尝试编写原始 SQL 查询来获取所有需要的数据。
理想的结果是一个特征过滤的产品数组,其中所有产品相关的特征作为 JSON 响应参数。
const products = [
{
id: 1,
title: 'Pipe 1',
price: 3000,
discount: 500,
characteristics: [
{
id: 1,
name: 'diameter',
value: '120 mm',
},
{
id: 2,
name: 'color',
value: 'black',
},
],
},
{
id: 2,
title: 'Pipe 2',
price: 5000,
discount: 0,
characteristics: [
{
id: 1,
name: 'diameter',
value: '120 mm',
},
{
id: 2,
name: 'color',
value: 'blue',
},
],
},
];
【问题讨论】:
标签: knex.js objection.js