【发布时间】: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