首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >knex (与Expressjs一起使用)和postgresSQL: String在SQL中自动由knex引用。

knex (与Expressjs一起使用)和postgresSQL: String在SQL中自动由knex引用。
EN

Stack Overflow用户
提问于 2020-08-16 12:00:26
回答 1查看 644关注 0票数 0

当我试图使用knex在SQL中传递一个值时,我遇到了一个问题。

代码语言:javascript
运行
复制
app.get('/home/:topbarMenuPath', (req, res)=> {
  const { topbarMenuPath } = req.params;

  var toStringQuery =
  db.select('tm1.menu_name','tm1.seq','tm1.menu_path','tm1.menu_id')
  .from('tb_menu as tm1')
  .join('tb_menu as tm2', function() {
    this.on('tm1.parent_menu_id', '=', 'tm2.menu_id')
      .andOn('tm2.menu_level', '=', 1)
      .andOn('tm1.menu_level', '=', 2)
      .andOn('tm2.menu_path','=',topbarMenuPath)
  }).toString()
  ;
  console.log('toStringQuery',toStringQuery);
});

如果我将':topbarMenuPath‘作为'hello’传递,console.log输出将显示如下:

代码语言:javascript
运行
复制
select "tm1"."menu_name", "tm1"."seq", "tm1"."menu_path", "tm1"."menu_id" 
from "tb_menu" as "tm1" 
inner join "tb_menu" as "tm2" on "tm1"."parent_menu_id" = "tm2"."menu_id" 
and "tm2"."menu_level" = 1
and "tm1"."menu_level" = 2 
and "tm2"."menu_path" = "hello"

Postgres似乎无法识别双引号"hello",当我试图将SQL发送到Postgres时,它显示了一个错误。错误:

代码语言:javascript
运行
复制
{
    "length": 166,
    "name": "error",
    "severity": "ERROR",
    "code": "42703",
    "position": "251",
    "file": "d:\\pginstaller_12.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_relation.c",
    "line": "3359",
    "routine": "errorMissingColumn"
}

有任何方法可以得到SQL单引号如下图所示吗?

代码语言:javascript
运行
复制
and "tm2"."menu_path" = 'hello'

而不是

代码语言:javascript
运行
复制
and "tm2"."menu_path" = "hello"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-16 13:59:30

是的,来自医生们

如果需要在联接中而不是在列中使用文字值(字符串、数字或布尔值),请使用knex.raw。

代码语言:javascript
运行
复制
knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin']))
Outputs:
select * from `users` inner join `accounts` on `accounts`.`type` = 'admin'

对你来说,这意味着.andOn('tm2.menu_path', '=', knex.raw('?', [topbarMenuPath]))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63436630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档