@Entity({ name: 'event' }) export class EventEntity extends AbstractIdEntity<EventDto> {…
- User
@Entity({ name: 'event' }) export class EventEntity extends AbstractIdEntity { @Column({ nullable: false }) name: string;
code@Column({ nullable: false, type: 'int' }) color: number; @Column({ nullable: true, type: 'date' }) date: Date; @ManyToOne(() => LocationEntity, { nullable: true }) location: LocationEntity; dtoClass = EventDto;} @Entity({ name: 'location' }) export class LocationEntity extends AbstractIdEntity { @Column({ nullable: true }) name: string;
code@Column({ nullable: true, type: 'int' }) color: number; @OneToMany(() => EventEntity, (event) => event.location, { nullable: true }) events: EventEntity[]; dtoClass = LocationDto;} based on these two entitites , are they correct and will they not create a circular dependency?
- Assistant
Yes, these two entities appear to be correct and there is no circular dependency between them. The
EventEntityhas aManyToOnerelationship with theLocationEntity, which means that an event can have only one location but a location can be associated with multiple events. On the other hand, theLocationEntityhas aOneToManyrelationship with theEventEntity, which means that a location can have multiple events associated with it. This is a common pattern in database design and does not create a circular dependency. - User
then why do i get throw new Error(
A circular dependency has been detected (property key: "${key}"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers ("type: () => ClassType").); ^ Error: A circular dependency has been detected (property key: "location"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers ("type: () => ClassType"). error when running my nest app - Assistant
This error occurs when there is a bidirectional relationship between two entities and both have the
ManyToOneandOneToManydecorators pointing to each other, causing a circular dependency.To resolve the issue, you need to use the
lazyoption in the relationship decorator to specify that the relationship should be resolved lazily using a closure. This is done by changing the decorator fromManyToOnetoManyToOne(() => LocationEntity, {lazy:true})andOneToManytoOneToMany(() => EventEntity, (event) => event.location, {lazy:true}).Here's an updated version of your code with the lazy option implemented:
code