在TypeORM中,如何查询where子句中属性的属性?

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

我正在使用 NestJS 10 和 TypeORM 0.3.17。我已经创建了这个邮政编码实体,

import {
  Entity,
  PrimaryGeneratedColumn,
  ManyToOne,
  JoinColumn,
  Column,
  Unique,
} from 'typeorm';
import { Country } from './country.entity';
import { Region } from './region.entity';

@Entity()
@Unique(['zipCode', 'region'])
export class ZipCode {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  zipCode: string;

  @Column()
  city: string;

  @ManyToOne((type) => Region, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'region_id', referencedColumnName: 'id' })
  region: Region;
}

与此关联的区域实体

@Entity()
@Unique(['name', 'country'])
export class Region {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column()
  abbrev: string;

  @ManyToOne((type) => Country)
  @JoinColumn({ name: 'country_id', referencedColumnName: 'id' })
  country: Country;
}

我正在尝试弄清楚如何编写 TypeORM 查询,以便我可以根据邮政编码和区域相关的国家/地区代码搜索邮政编码。我试过这个

export class ZipCodeRepository extends Repository<ZipCode> {
    ...
  async findByZipCode(zipCode: string, countryCode: string): Promise<ZipCode> {
    return this.zipCodeRepository.findOne({
      select: ['zipCode', 'city'],
      relations: ['region'],
      where: { region: { country: {countryCode: countryCode} } },
    });

但是由于编译错误而失败,

Type '{ country: { countryCode: string; }; }' is not assignable to type 'boolean | FindOperator<any> | FindOptionsWhere<Region> | FindOptionsWhere<Region>[] | EqualOperator<Region>'.
  Types of property 'country' are incompatible.
    Object literal may only specify known properties, and 'countryCode' does not exist in type 'FindOperator<any> | FindOptionsWhere<Country> | FindOptionsWhere<Country>[] | EqualOperator<Country>'.

构建关联查询的正确方法是什么?

sql nestjs typeorm relation
1个回答
0
投票

您应该像这样添加该地区的国家关系:

async findByZipCode(zipCode: string, countryCode: string): Promise<ZipCode> {
    return this.zipCodeRepository.findOne({
      select: ['zipCode', 'city'],
      relations: ['region','region.country'],
      where: { region: { country: {countryCode: countryCode} } },// ensure countryCode field must have inside country
    });
© www.soinside.com 2019 - 2024. All rights reserved.