过滤某些实体的所有请求?

时间:2020-06-24 09:45:50

标签: typeorm

在某些情况下,能够在特定条件下注释特定实体的所有查询(或应用程序中的所有查询)会非常有利。例如当我使用USER模型并且希望诸如findOnefind之类的查询不返回user实例的密码和盐时。我不想从每个查询中删除属性-相反,我只想执行一次。

另一个用例是针对我的应用程序中的特定租户进行过滤。

到目前为止,我还没有使用TypeORM看到此功能。它存在吗?

1 个答案:

答案 0 :(得分:2)

您可以将select: false添加到实体中的列,这将使您能够默认情况下不选择此列。

例如:

@Entity('user')
export class USER {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 255 })
  firstName: string;

  @Column({ type: 'text', default: null, select: false }) <-- here
  salt: string;

  @Column({ type: 'varchar', length: 255, default: null, select: false }) // <-- here
  password: string;
}

但是如果您不得不选择这些列,则可以为此实体使用QueryBuilderaddSelect()这些列:

this.userRepo
  .createQueryBuilder('user')
  .where({ firstName: 'John' })
  .addSelect(['user.salt', 'user.password'])
  .getOne();