在我的查询中,我使用的是 TypeORMfind
选项。我怎样才能IS NULL
在where
条款中有条件?
5 回答
另一种方法是您可以使用IsNull()
函数,例如:
import { IsNull } from "typeorm";
return await getRepository(User).findOne({
where: {
username: IsNull()
}
});
如果有人在寻找 NOT NULL,它会是这样的:
import { IsNull, Not } from "typeorm";
return await getRepository(User).findOne({
where: {
username: Not(IsNull())
}
});
您可以为此目的使用QueryBuilder :
const users = await userRepository.createQueryBuilder("user")
.where("user.name IS NULL")
.getMany();
除了hungneox answer之外,您应该知道您有很多预定义的运算符。
这是来自定义它的文件:
export declare type FindOperatorType = "not" |
"lessThan" |
"lessThanOrEqual" |
"moreThan" |
"moreThanOrEqual" |
"equal" |
"between" |
"in" |
"any" |
"isNull" |
"like" |
"raw";
以上每一项都可以在此处的“操作员”部分中设置:
{
where: {
propertyToCheck: <Operator>
}
}
您只需从 @typeorm 包中导入它,然后像使用函数一样使用它,例如 LessThan():
import { Repository, Between, IsNull, LessThan } from 'typeorm';
{
where: {
age: LessThan(50)
}
}
这是了解您是否想掌握 typeorm 的非常强大且重要的工具 :) 祝您好运!
我真的不喜欢为此使用QueryBuilder
来自 TypeORM 的内容,因为在我看来,在使用FindConditions
.
不幸的是,使用如下代码:
async articleRequests(
accepted?: ArticleRequestAcceptance,
): Promise<ArticleRequest[]> {
const where: FindConditions<ArticleRequest>[] | FindConditions<ArticleRequest> = {};
if (accepted !== undefined) {
switch (accepted) {
case ArticleRequestAcceptance.Accepted:
where.accepted = true;
break;
case ArticleRequestAcceptance.Rejected:
where.accepted = false;
break;
case ArticleRequestAcceptance.NotReviewedYet:
where.accepted = undefined;
break;
}
}
return await ArticleRequest.find({ where }).catch(reason => {
throw reason.message;
});
}
TypeORM 为您提供如下所示的 SQL 查询:
SELECT '...' WHERE "ArticleRequest"."accepted" = NULL
因为,从 TypeORM 日志输出中可以看出... WHERE "ArticleRequest"."accepted" = @0 -- PARAMETERS: [null]
,具有undefined
值的属性(accepted
在这种情况下)在参数数组中被转换为null
s,然后它们被简单地注入 SQL 字符串。
SQL 标准规定,对于比较运算符(例如or ) ,任何与null
结果的比较在 SQL 中都应该没有意义,但原因是与 null 比较意味着“未知”,因此此类查询为什么不返回任何结果。如果你问我,SQL 在这里坏了。null
=
<>
所以,是的,正如@hungneox 所说,解决方案是使用IsNull()
which 返回一个特殊FindOperator
的特定列,您需要查询 asIS NULL
和 not = NULL
。
像这样:
if (accepted !== undefined) {
switch (accepted) {
case ArticleRequestAcceptance.Accepted:
where.accepted = true;
break;
case ArticleRequestAcceptance.Rejected:
where.accepted = false;
break;
case ArticleRequestAcceptance.NotReviewedYet:
where.accepted = IsNull();
break;
}
}