【问题标题】:Knex select static "column" as aliasKnex 选择静态“列”作为别名
【发布时间】:2018-07-30 01:37:07
【问题描述】:

我正在尝试使用 Postgres 在 Knex 中实现以下查询,以返回静态“$type”列(用于向 GraphQL 服务器提供类型提示):

select *, 'Patrol' as "$type" from patrol;

当我使用 Knex 查询生成器时,它会破坏引号:

knex('patrol')
  .select(['*', `'Patrol' as "$type"`])
  .where('id', 12345)
  .first()

返回

ERROR:  column "'Patrol'" does not exist at character 11
STATEMENT:  select *, "'Patrol'" as """$type""" from "patrol" where "id" = $1 limit $2

我可以使用knex.raw() 构造查询,但我真的不想这样做:

knex.raw(
  `SELECT *, 'Patrol' as "$type" FROM patrol WHERE id = '${value}' LIMIT 1;`
)

我应该如何构造select() 语句以便查询生成器正确解释它?

【问题讨论】:

    标签: javascript postgresql graphql knex.js


    【解决方案1】:

    我能够通过在select 中使用knex.raw() 使其工作:

    knex('patrol')
      .select(knex.raw(`*, 'Patrol' as "$type"`)
      .where('id', 12345)
      .first()
    

    【讨论】:

      【解决方案2】:

      这行不通 (https://runkit.com/embed/g5h8qwmeyoyh)?

      const Knex = require('knex');
      
      const knex = Knex({
        client: 'pg'
      });
      
      knex('patrol')
        .select('*', 'Patrol as $type')
        .where('id', 12345)
        .toSQL()
      
      // select *, "Patrol" as "$type" from "patrol" where "id" = ?
      

      或者你真的想在每一行添加带有别名'$type'的字符串文字Patrol?如果如此原始是这样的方式,让方言转义/引号正确(https://runkit.com/embed/12av9qxxwgyj):

      require('sqlite3');
      const Knex = require('knex');
      
      const knex = Knex({
        client: 'sqlite',
        connection: ':memory:'
      });
      
      await knex.schema.createTable('test', t => {
        t.increments('id').primary();
        t.string('data');
      });
      
      await knex('test').insert([{ data: 'foo' }, { data: 'bar' }]);
      
      console.dir(
        await knex('test').select('*', knex.raw('? as ??', ['Patrol', '$type']))
      );
      

      【讨论】:

      • 是的,将 'Patrol' 添加为别名为 "$type" 的字符串文字正是我想要做的。我能够使用raw 完成它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2012-06-11
      • 2020-10-26
      • 2012-03-23
      • 1970-01-01
      相关资源
      最近更新 更多