数据库的字符串模板只包含最后一部分



我看不到,这里缺少什么?count是我的方法的传入参数。

const allFields = `
select 
company_id,
company_name
from company
`;

然后:

const query = `${allFields} ORDER BY company_created_date DESC ` && count > 0 ? 'LIMIT' : '';

我只为查询返回文本"LIMIT"。至少我应该得到第一部分${allFields} ORDER BY company_created_date DESC

const query = `${allFields} ORDER BY company_created_date DESC ` && count > 0 ? 'LIMIT' : '';

正在解析为:

if(`${allFields} ORDER BY company_created_date DESC`  && count > 0){
query = 'LIMIT';
} else {
query = '';
}

基本上字符串部分总是true,所以如果计数大于0,你会得到'LIMIT',否则是''

如果我得到了你想要的,试试这个:

const query = `${allFields} ORDER BY company_created_date DESC ${count > 0 ? 'LIMIT' : ''}`;

&&不是连接运算符,但看起来您正试图连接到查询的末尾。连接是使用+完成的。

你应该在三进制的两边加上括号。它的优先级较低,因此加法表达式将被视为条件。

const query = `${allFields} ORDER BY company_created_date DESC ` + (count > 0 ? `LIMIT ${count}` : '');

最新更新