21

在我的查询中,我使用的是 TypeORMfind选项。我怎样才能IS NULLwhere条款中有条件?

4

5 回答 5

61

另一种方法是您可以使用IsNull()函数,例如:

import { IsNull } from "typeorm";
return await getRepository(User).findOne({
    where: { 
      username: IsNull()
    }
});
于 2019-01-25T11:23:57.823 回答
43

如果有人在寻找 NOT NULL,它会是这样的:

import { IsNull, Not } from "typeorm";

return await getRepository(User).findOne({
    where: { 
      username: Not(IsNull())
    }
});

于 2021-02-10T21:41:14.857 回答
13

您可以为此目的使用QueryBuilder :

const users = await userRepository.createQueryBuilder("user")
     .where("user.name IS NULL")
     .getMany();
于 2017-10-25T10:05:54.007 回答
3

除了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 的非常强大且重要的工具 :) 祝您好运!

于 2019-06-25T18:33:54.370 回答
2

我真的不喜欢为此使用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在这种情况下)在参数数组中被转换为nulls,然后它们被简单地注入 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;
    }
  }
于 2019-10-29T22:38:34.717 回答