如何在Typeorm中查询虚拟列

问题描述 投票:0回答:1

我有一个带有虚拟列 slugWithUuid 的实体声明。如何在查询中查询此类列。

@Entity()
export class Course extends DefaultCredential {
  @Column({ type: 'varchar', length: 75 })
  title: string;

  @Column({ type: 'varchar', length: 50 })
  slug: string;

  @Column({ type: 'json', nullable: true })
  additionalInfoJSON: any;

  slugWithUuid: string;
  @AfterLoad()
  setCustomProperty() {
    this.slugWithUuid =
      this.slug + '-' + JSON.parse(this.additionalInfoJSON)?.uuid;
  }

  @BeforeInsert()
  insertShortUUID() {
    const shortUUID = generateUUID(6);
    const additionalInfo = {
      ...this.additionalInfoJSON,
      uuid: shortUUID,
    };
    this.additionalInfoJSON = JSON.stringify(additionalInfo);
  }
}

这是我的查询示例:

async findBySlug(slug: string) {
    const entity = await this.repos.findOne({
      where: { slugWithUuid: slug }
    });

    if (!entity) {
      throw new NotFoundException('Entity not found with this slug');
    }
    return entity;
  }

是否有任何其他方法来声明此虚拟列以便能够在查询中对其进行过滤,因为此查询暂时返回此错误:

[Nest] 637270 - 10/03/2024, 9:37:42 AM 错误 [ExceptionsHandler] 在“课程”中找不到属性“slugWithUuid”。确保您的 查询正确。 EntityPropertyNotFoundError:属性“slugWithUuid” 在“课程”中找不到。确保您的查询正确。

javascript node.js nestjs typeorm
1个回答
0
投票

经过长时间的研究,我找到了这个解决方案:

@VirtualColumn({
    query: (alias) => {
      const uuidSelect = `JSON_UNQUOTE(JSON_EXTRACT(JSON_UNQUOTE(${alias}.additionalInfoJSON), '$.uuid'))`;
      return `CONCAT(
        ${alias}.slug,
        '-',
        ${uuidSelect}
      )`;
    },
  })
  slugWithUuid: string;

它用@VirtualColumn重新声明slugWithUuid,现在我可以查询它了。

© www.soinside.com 2019 - 2024. All rights reserved.