【问题标题】:Can't filter data according foreign key in TypeOrm无法根据 TypeOrm 中的外键过滤数据
【发布时间】:2021-06-06 18:12:49
【问题描述】:

我使用 Nest Js、PostgresQl 和 Typeorm。 我在 typeorm 中有这两个实体:

export class Meta {
    @PrimaryGeneratedColumn({name: "metaId"})
    metaId: number;

    @Column({nullable: true})
    name: string;

    @OneToMany(() => TablesEntity, table => table.metaId, {eager: true, cascade: true})
    metaTables: TablesEntity[];
}
//
export class TablesEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => Meta, meta => meta.metaTables)
    @JoinColumn({name: "metaId"})
    metaId: Meta;
}

现在我想根据过滤值获取所有数据:

const meta = await this.metaRepository.findOne({
  where: {
    metaId: metaId,
    metaTables: [{
        status: Not('white')
    }]
  },
  relations: ["metaTables"]
});

所以我想获取所有没有状态的数据:“白色”,但我得到一个错误:No entity column "metaTables" was found
为什么会出现这个错误,如何解决?

【问题讨论】:

  • 也许是一个愚蠢的问题,但是有没有可能,你忘记在 Meta 类上使用 Entity 装饰器,所以 typeorm 没有为它生成表?
  • @Balint Csak,没有metaTables: [{ status: Not('white') }] 我得到所有数据,所以它工作,但我需要过滤没有状态白色的元表。
  • 也许也是一个愚蠢的问题,但是您是否有机会忘记将状态列添加到 TablesEntity 中?
  • @Asking 谢谢,这有助于回答您的问题。请稍后再给我们一个更准确的例子,因为这有点误导。

标签: node.js nestjs typeorm


【解决方案1】:

不幸的是,typeorm 无法处理您在上面尝试使用的这些方法 (findOne, findMany, update etc...) 中的嵌套查询。然而,有几种不同的解决方案,但它们都使用了更复杂的方法。

最相似的解决方案是如果您使用find 方法,但使用查询构建器的所有参数配置它:

await connection.getRepository(Meta).findOne({
  where: (qb: SelectQueryBuilder<Meta>) => {
    qb.where({
      metaId: metaId,
    }).andWhere("metaTables.status != :status", { status: 'white' });
  },
  join: {
    alias: "meta",
    innerJoin: {
      metaTables: "meta.metaTables",
    },
  },
});

另一种方法是,如果您只是使用查询构建器并构造以下查询:

await connection
  .getRepository(Meta)
  .createQueryBuilder("meta")
  .innerJoin("meta.metaTables", "metaTables")
  .where({ metaId: metaId })
  .andWhere("metaTables.status != :status", { status: "white" })
  .getOne();

还有第三种解决方案,但它仅适用于&lt;=0.2.24。此解决方案以这种方式构造 where 对象,每个关系过滤器显示为单个字符串,其中列与点连接。这是一个例子:

await connection.getRepository(Meta).findOne({
  where: {
    metaId: metaId,
    "metaTables.status": Not("white"),
  },
  relations: ["metaTables"],
});

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2022-11-23
    • 2020-01-21
    • 2011-02-19
    • 2020-07-03
    相关资源
    最近更新 更多