Knex 选择静态“列”作为别名

gra*_*amb 6 javascript postgresql knex.js graphql

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

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

当我使用 Knex 查询构建器时,它会修改引号:

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

退货

ERROR:  column "'Patrol'" does not exist at character 11
STATEMENT:  select *, "'Patrol'" as """$type""" from "patrol" where "id" = $1 limit $2
Run Code Online (Sandbox Code Playgroud)

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

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

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

gra*_*amb 8

我能够通过knex.raw()在以下内容中使用来使其工作select

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


Mik*_*stö 5

这不起作用(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" = ?
Run Code Online (Sandbox Code Playgroud)

或者你真的想Patrol在每一行中添加别名为“$type”的字符串文字?如果这样原始的方法是让方言转义/引号正确(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']))
);
Run Code Online (Sandbox Code Playgroud)