In my database, I have one species record and two cat records
Cat Table
id size species_id
1 large 5
1 small 5
Species Table
id
5
@Entity('cat')
export class Cat {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'text' })
size: string;
@ManyToOne(() => Species)
@JoinColumn({ name: 'species_id', referencedColumnName: 'id' })
speciesId: string;
}
@Entity('species')
export class Species {
@PrimaryGeneratedColumn('uuid')
id: string;
}
const entity = await this.catRepository.findOneOrFail(catId);
the entity
only returns {id: catId, size: 'large'}
but does not return the speciesId
even though there's a species id in the cat record in my database.
I am new to TypeORM and I think one of the things ManyToOne does is to establish FK constraints. Why is the query behavior the way it is and how can I get the species id to return without having to use joins?
CodePudding user response:
In your situation I think you are missing 1 extra column in Cat
entity. Column in which you will store species_id
, or if you wish to make it accurate, then use singular specie_id
.
@Entity('cat')
export class Cat {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'text' })
size: string;
@Column({type: 'uuid' })
specie_id: string;
@ManyToOne(() => Species)
@JoinColumn({ name: 'specie_id', referencedColumnName: 'id' })
species: Species;
}
More info you can find in typeorm documentation: https://typeorm.io/#/many-to-one-one-to-many-relations