node.js - 字段名与数据库中的列名不同
问题描述
我刚开始在 mysql 中使用 graphql,我想知道是否可以在 graphql 查询中使用与我的数据库中的列名不同的名称。
例如,我有一个表用户,其中包含用户名和密码列,当我为模式定义类型时,我有以下内容:
const unidadesMedidaInternaType = new GraphQLObjectType({
name: 'unidadesMedidaInterna',
fields: () => ({
userName: { type: GraphQLID },
password: { type:GraphQLString }
})
});
解析器:
resolve (parent, args) {
return pool.query(`SELECT * FROM users`);
}
所以我必须这样查询:
{
users {
userName,
password
}
}
我想在查询中使用不同的名称,如下所示:
{
users {
Name,
secret
}
}
我尝试更改类型定义中的字段名称,但查询结果充满了空值。
解决方案
为了在查询中使用不同的名称,您有 2 个选项:
选项 1:使用别名运行查询:您可以使用别名运行查询,例如
{
users {
Name: userName,
secret: password
}
}
在这种情况下,您只是在执行时重命名字段名称,因此原始名称仍可用于查询。
选项 2:将查询结果映射到GraphQLObject
类型。
首先重命名字段:
const unidadesMedidaInternaType = new GraphQLObjectType({
name: 'unidadesMedidaInterna',
fields: () => ({
Name: { type: GraphQLID },
secret: { type:GraphQLString }
})
});
然后映射查询结果以匹配字段:
resolve (parent, args) {
const result = pool.query(`SELECT * FROM users`);
// If the result of the query is an array then you have to map its items
return { Name: result.userName, secret: result.password }
}
希望能帮助到你。
推荐阅读
- mysql - 使用 mysql 从 Wordpress 网站在 Laravel 应用程序中插入数据
- flutter - Flutter_Swiper 文本覆盖图像
- sql - Oracle父子查询
- sql - 使用 SQL 计算 Fifo
- android - 如何避免本地 Web 应用程序数据被擦除?
- node.js - Nodejs odbc - 插入语句不起作用
- javascript - 尽管使用单独的测试文件,RegExp 匹配仍返回 null
- linux - 在linux终端中的gz中逐个文件压缩文件
- python - PANDAS - 如何在分组后获得经过的天数
- python - Seaborn:并排绘制 2 个配对图