I have an entity Store that stores in itself
@Entity('shops')
export class ShopEntity{
@PrimaryGeneratedColumn()
id: number;
@OneToOne(() => ScheduleEntity)
@JoinColumn()
schedule: ScheduleEntity;
}
I also have a Schedule entity
@Entity('schedules')
export class ScheduleEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('jsonb')
monday: DayDto;
}
In the shop entity, I insert such an ordinary thing
@AfterInsert()
async createDefaultSchedule() {
const schedule = new ScheduleEntity();
const initialDay: DayDto = {
bags: 0,
enabled: true,
timeEnd: '16:00',
timeStart: '15:00',
};
schedule.monday = initialDay;
const scheduleRepo = await Data.getRepository(ScheduleEntity);
scheduleRepo.save(schedule);
}
But when creating a shop, I get an error:
EntityMetadataNotFoundError: No metadata for "ScheduleEntity" was found.
I don’t even know if it’s possible to do it this way, because there are slight doubts about it, so that when creating an entity, I would create another entity in the relationship
2
Answers
As the @Eranga Heshan said, Indeed, it is better to use entity creation at the time of creating another entity when requesting. What will happen like
But for this you need to configure the oneToOne relationship correctly, and then everything will work (used the documentation)
Just like @nbk mentioned your
shops
table has a one-to-one relationship withschedules
table.Based on your entity definition, a
ShopEntity
cannot exist without creating its relatedScheduleEntity
becauseShopEntity
has the foreign key constraint (@JoinColumn()
decorator defines which entity is going to save the foreign key).To fix this specific issue, you can modify your entities like this:
Now your
ShopEntity
can exist without first having aScheduleEntity
.However, I believe you don’t need to use
@AfterInsert
at all here. You can simply save both entities at once like below: