Sql 如何在typeorm find options中设置is null条件?
在我的查询中,我使用的是typeorm find选项, 我如何在where子句中使用IS NULL条件?您可以为此使用:Sql 如何在typeorm find options中设置is null条件?,sql,where-clause,typeorm,typeorm-activerecord,Sql,Where Clause,Typeorm,Typeorm Activerecord,在我的查询中,我使用的是typeorm find选项, 我如何在where子句中使用IS NULL条件?您可以为此使用: const users = await userRepository.createQueryBuilder("user") .where("user.name IS NULL") .getMany(); 另一种方法是可以使用IsNull()函数,例如: 从“typeorm”导入{IsNull}; return wait getRepository(用户)
const users = await userRepository.createQueryBuilder("user")
.where("user.name IS NULL")
.getMany();
另一种方法是可以使用
IsNull()
函数,例如:
从“typeorm”导入{IsNull};
return wait getRepository(用户)。findOne({
其中:{
用户名:IsNull()
}
});
除了hungneox answer,您还应该知道您有很多预定义的运算符
这来自定义它的文件:
export declare type FindOperatorType = "not" |
"lessThan" |
"lessThanOrEqual" |
"moreThan" |
"moreThanOrEqual" |
"equal" |
"between" |
"in" |
"any" |
"isNull" |
"like" |
"raw";
可在此处的“操作员”部分设置上述各项:
{
where: {
propertyToCheck: <Operator>
}
}
如果您想掌握typeorm,这是一个非常强大和重要的工具:)
祝你好运 我真的不想使用TypeORM中的
QueryBuilder
,因为在我看来,在使用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日志输出中可以看出,。。。其中“ArticleRequest”。“accepted”=@0--参数:[null]
,具有未定义的值的属性(在本例中为accepted
)在参数数组中转换为null
s,然后它们被简单地注入SQL字符串
SQL标准说,任何与null
的比较都会导致null
,因此对于比较运算符,如=
或
,在SQL中,这应该是没有意义的,但其原因是与null的比较意味着“未知”,因此为什么这样的查询不会返回任何结果。如果你问我,SQL在这里是坏的
是的,正如@hungneox所说,解决方案是使用IsNull()
,它返回一个特殊的FindOperator
,用于需要查询的特定列,因为为NULL而不是=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;
}
}
如果有人正在查找NOT NULL,则如下所示:
import { IsNull, Not } from "typeorm";
return await getRepository(User).findOne({
where: {
username: Not(IsNull())
}
});
这是手动方式,但是如果你看到它可以为你做这件事-我只是不确定如何做。如果你不需要空值,也许它可以帮助某人使用:。其中(“user.name不是空的”)
如果你想要相反的方式(当寻找非空列时)。用那种方法包装<代码>非(IsNull())
import { IsNull, Not } from "typeorm";
return await getRepository(User).findOne({
where: {
username: Not(IsNull())
}
});