【问题标题】:TypeORM & NestJS: TypeError: Cannot read properties of undefined (reading 'joinColumns')TypeORM & NestJS: TypeError: Cannot read properties of undefined (reading 'joinColumns')
【发布时间】:2022-07-09 17:48:34
【问题描述】:

我有一个产品实体和类别实体。产品与类别具有多对一关系,而类别与产品具有太多关系。当我尝试加载某个类别的相关产品时出现错误。

我有一个业务产品类别实体如下:

import { Entity, Column, ManyToOne, OneToMany, JoinColumn } from 'typeorm';
import { BaseEntity } from './base';
import { BusinessProductsEntity } from './product.entity';

@Entity('business_product_category')
export class BusinessProductCategoryEntity extends BaseEntity {
  @Column('varchar', { length: 50 })
  public category: string;

  @Column('text', { nullable: true })
  public description: string;

  @OneToMany(
    () => BusinessProductCategoryEntity,
    products => products.category,
  )
  products: BusinessProductsEntity[];
}

而业务产品实体为:

import { Entity, Column } from 'typeorm';
import { BaseEntity } from './base';

@Entity('business_products')
export class BusinessProductsEntity extends BaseEntity {
  @Column('jsonb', { nullable: true })
  public details: any;

  @Column('text', { nullable: true, name: 'additional_information' })
  public additionalInformation: string;

  @Column('int', { default: 0, name: 'total_stock' })
  public totalStock: number;

  @Column('bigint', { default: 0 })
  public price: number;

  @ManyToOne(() => BusinessProductCategoryEntity, { eager: true })
  @JoinColumn({ name: 'business_product_category_id' })
  public category: BusinessProductCategoryEntity;
}

当我尝试leftJoin 并加载某个类别的所有产品时,我收到错误: TypeError: Cannot read properties of undefined (reading 'joinColumns')

我用来加载关系的代码:

// doesn't work
this.categoryRepository.find({ relations: ['products'] });

// doesn't work either
this.categoryRepository
      .createQueryBuilder('category')
      .leftJoinAndSelect('category.products', 'products')
      .getMany();

【问题讨论】:

  • docs here 建议在O2M和M2O关系中可以省略@JoinColumn。离开它可能会产生一些不利影响(如果非默认值,也许你可以明确指定列名)

标签: typescript nestjs typeorm node.js-typeorm


【解决方案1】:

尝试通过删除node_modules 并在之前运行npm cache clean --force 来重新安装依赖项。还要检查您的节点版本是否是最新的。这些操作帮助我解决了类似的问题。

【讨论】:

    【解决方案2】:

    我在更新Entity 文件后遇到了这个错误,我们通过删除dist 文件夹并再次运行我的项目来解决它

    【讨论】:

      【解决方案3】:

      您没有为BusinessProductsEntity 指定inverse side

      @ManyToOne(() => BusinessProductCategoryEntity, (p) => p.products, { eager: true })
      

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 2021-11-03
        • 2021-11-08
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 2021-12-11
        • 1970-01-01
        相关资源
        最近更新 更多