首页 > 解决方案 > 字段名与数据库中的列名不同

问题描述


我刚开始在 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
  }
}

我尝试更改类型定义中的字段名称,但查询结果充满了空值。

标签: node.jsgraphql

解决方案


为了在查询中使用不同的名称,您有 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 }
}

希望能帮助到你。


推荐阅读