GraphQL/Sequelize : SQL 别名
GraphQL/Sequelize : SQL alias
使用的技术:
- 用于 graphQL 的 Apollo-server-express
- Sequelize 连接到 SQL 服务器
我继承了一个数据库,其中的字段不遵循任何命名约定。有些有空格和特殊字符。为了避免任何问题,我在解析器查询中为这些字段使用了 SQL 别名:
const productAttributes = [
'SAP',
['Unit/V', 'UnitVol']];
...
Query: {
product: async (parent, {SAP} , { models }) => {
const result = await models.Product.find( {
where: {
SAP: SAP
},
attributes:productAttributes,
});
return result;
},
...
GraphQL 架构设置为:
type Product {
SAP: String!
UnitVol: Int
}
从 playground 执行查询时,来自模型的字段 "SAP" 已填满,但字段别名 "UnitVol" 设置为空(参见图像 GraphQL result).
仔细观察,Sequelize 执行了以下 SQL 语句:
Executing (default): SELECT [SAP], [Unit/V] AS [UnitVol] FROM [product codes] WHERE [product codes].[SAP] = N'22736';
上述查询结果 returns 带有别名的值(console.log(结果)的摘录):
product codes {
dataValues:
{ SAP: '22736',
UnitVol: 9 }
},
因此解析器返回的 SQL 别名和 graphQL 模式之间似乎缺少 link。任何帮助深表感谢。
我找到了解决方案:
我 return 结果中的 'datavalues' 数组,而不是 return 续集结果:
return !result ? [] : result.dataValues;
我必须控制结果不为空(graphQL 请求没有条目)。如果有人有更清晰的答案,我会很乐意测试它!谢谢。
使用的技术:
- 用于 graphQL 的 Apollo-server-express
- Sequelize 连接到 SQL 服务器
我继承了一个数据库,其中的字段不遵循任何命名约定。有些有空格和特殊字符。为了避免任何问题,我在解析器查询中为这些字段使用了 SQL 别名:
const productAttributes = [
'SAP',
['Unit/V', 'UnitVol']];
...
Query: {
product: async (parent, {SAP} , { models }) => {
const result = await models.Product.find( {
where: {
SAP: SAP
},
attributes:productAttributes,
});
return result;
},
...
GraphQL 架构设置为:
type Product {
SAP: String!
UnitVol: Int
}
从 playground 执行查询时,来自模型的字段 "SAP" 已填满,但字段别名 "UnitVol" 设置为空(参见图像 GraphQL result).
仔细观察,Sequelize 执行了以下 SQL 语句:
Executing (default): SELECT [SAP], [Unit/V] AS [UnitVol] FROM [product codes] WHERE [product codes].[SAP] = N'22736';
上述查询结果 returns 带有别名的值(console.log(结果)的摘录):
product codes {
dataValues:
{ SAP: '22736',
UnitVol: 9 }
},
因此解析器返回的 SQL 别名和 graphQL 模式之间似乎缺少 link。任何帮助深表感谢。
我找到了解决方案:
我 return 结果中的 'datavalues' 数组,而不是 return 续集结果:
return !result ? [] : result.dataValues;
我必须控制结果不为空(graphQL 请求没有条目)。如果有人有更清晰的答案,我会很乐意测试它!谢谢。