In my NestJS application with postgres db I have these 3 entities: User, Writer, Book
and a class named UserBaseEntity.
export class UserBaseEntity {
@PrimaryColumn()
id: string;
@OneToOne(() => UserEntity, { primary: true, cascade: true })
@JoinColumn({ name: 'id'})
user: UserEntity
@Entity()
export class WriterEntity extends UserBaseEntity implements Writer {
@Column()
name: string;
@OneToMany(() => BookEntity)
books: BookEntity[];
@Entity()
export class BookEntity extends BaseEntity {
@Column()
name: string;
@ManyToOne(() => WriterEntity, writer => writer.books)
@JoinColumn({referencedColumnName: 'id', name: 'writerId'})
writer?: WriterEntity;
@Column()
writeId: string;
Writer extends UserBaseEntity class which makes his Primary key(id) be be a foreign key to UserEntity table(id).
When I tried to make One To Many relation between Writer and Book I am getting this error
QueryFailedError: foreign key constraint "FK_XXX" cannot be implemented
or
writerId violates not-null constraint
So, there is a problem I guess with Postgres when there is this kind of situation: book.writerId(FK) -> writer.id(FK) -> user.id
Any idea that maybe can help?
A solution I have found is to move the oneToMany decorator from writer entity to user entity. I hope to find a more elegant and logic suitable way.
Thanks