knex.js - 如何将带有别名的 SQL LEFT 放入书架?
问题描述
我需要这个SQL
(在 mysql 控制台中完美运行):
SELECT LEFT(authors.last_name,1) AS first_char
在"bookshelf.js"
.
当我走到这一步时:
let result = await qb.column('last_name').select().from('authors').as('first_char');
我无法得到
let result = await qb.column('last_name').select('LEFT(authors.last_name,1)').from('authors').as('first_char');
这个去。
它会导致以下错误:
Error: ER_BAD_FIELD_ERROR: Unknown column 'LEFT(authors.last_name,1)' in 'field list'
这对我来说没有意义,因为该列authors.last_name
仍然存在。
解决方案
.select()
防止 SQL 注入,因此您不能只是将随机 SQL 传递给它并期望它工作。您需要为此使用原始表达式:
qb.column('last_name').select(qb.raw('LEFT(authors.last_name,1)')).from('authors').as('first_char');
在这方面,从技术上讲,这不是一个书架问题,因为查询构建器只是 knex。