我们创建了一个辅助函数来创建更容易的地方。它与 eq、neq、lt 和 gt 配合使用效果良好。现在我们尝试添加 is null/is not null(对于日期列,不确定这是否重要)。
该函数的关键部分如下所示:
// This is ran in a loop for every attribute
const query = `${attribute}` ${comparator} :value${index}`;
// if the checked 'value' is NULL then use IsNull(), same for NOT NULL, otherwise simply use value
const params = { [`value${index}`]: value == 'NULL' ? IsNull() : value === 'NOT NULL' ? Not(IsNull()) : value};
// Add this (sub)query to the qb
qb.andWhere(query, params);
现在我们收到一条错误消息:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ’
_type
= ‘not’,_value
= ‘[object Object]‘,_useParameter
= true, `_multipl’ at line 1"
值是[object Object]
- 如果我们使用IsNotNull()
,这才有意义,对吗?
据我了解this comment 、 IsNull()
和 Not(IsNull())
应该像我们正在尝试的那样工作。
我们使用@nestjs/typeorm 7.1.5.
最佳答案
要检查 NULL,您需要
qb.andWhere(`${attribute} IS NULL`)
要检查 NOT NULL,您需要
qb.andWhere(`${attribute} IS NOT NULL`)
(注意:在这些情况下省略第二个参数,参数)。
从您的代码看来,您正在使用字符串值“NULL”和“NOT NULL”作为值参数,并将它们作为特殊情况进行检查。您的代码现在如下所示:
if ((value == 'NULL' && comparator == '=') || (value == 'NOT NULL' && comparator == '<>'))
qb.andWhere(`${attribute} IS NULL`);
if ((value == 'NOT NULL' && comparator == '=') || (value == 'NULL' && comparator == '<>'))
qb.andWhere(`${attribute} IS NOT NULL`);
else
qb.andWhere(`${attribute} ${comparator} :value${index}`, { [`value${index}`]: value});
(在上面的代码中,我检查了标准 SQL 比较运算符“=”和“<>”。如果您的 SQL 方言使用“eq”和“ne”代替“=”和“<>”,您在问题中提到的内容,您将需要更改上面的代码。如果是这样,请更新您的问题并添加适当的标签来说明您正在使用哪个 SQL 数据库)。
当您对此进行测试时,我建议您打开 TypeOrm 完整日志记录,以便您可以看到实际生成的 SQL,并且能够快速解决任何问题。请参阅TypeOrm logging .
关于sql - typeorm:如何正确使用IsNotNull/IsNull?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66045886/