Reputation: 387
I have a product entity and category entity. Product has a many to one relation to category and category has one too many with the product. When I try to load related products of a category I get an error.
I have a business product category entity as below:
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[];
}
And a business product entity as:
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;
}
When I try to leftJoin
and load all products of a category I get the error:
TypeError: Cannot read properties of undefined (reading 'joinColumns')
The code I am using to load the relation:
// doesn't work
this.categoryRepository.find({ relations: ['products'] });
// doesn't work either
this.categoryRepository
.createQueryBuilder('category')
.leftJoinAndSelect('category.products', 'products')
.getMany();
Upvotes: 1
Views: 19528
Reputation: 682
As per the document when join column is set with custom name and without referenced column name we need automatically set referenced column name - primary ids by default. As there is no primary column mentioned in the business_product_category
entity, add a referencedColumnName
in @JoinColumn
as such:
@ManyToOne(() => BusinessProductCategoryEntity, { eager: true })
@JoinColumn({ name: 'business_product_category_id', referencedColumnName:"// your intended column name" })
public category: BusinessProductCategoryEntity;
Upvotes: 1
Reputation: 5051
I faced this error after updating the Entity
file, we solved it with delete the dist
folder and running my project again
Upvotes: 2
Reputation: 100
Try to reinstall dependencies by deleting node_modules
and running npm cache clean --force
before. Also check your node version to be the latest. These actions helped me with a similar issue.
Upvotes: 1