问题描述
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输出将显示如下:
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时,它显示了一个错误。 错误:
{
"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像下面的单引号一样问好吗?
and "tm2"."menu_path" = 'hello'
代替
and "tm2"."menu_path" = "hello"
解决方法
是,来自the docs:
如果需要在联接而不是列中使用文字值(字符串,数字或布尔值),请使用knex.raw。
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','=',[topbarMenuPath]))
感谢鲁宾·赫斯卢特(Ruben Helsloot)的回答。我为解决问题提供了解决方法。
我从更改代码
.andOn('tm2.menu_path',topbarMenuPath)
到
.andOn('tm2.menu_path',[topbarMenuPath]))
如果topbarMenuPath是hello,则输出将如下所示。
and "tm2"."menu_path" = 'hello'