在我的資料庫中,我有一個物種記錄和兩個貓記錄
貓桌
id size species_id
1 large 5
1 small 5
物種表
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);
在entity唯一的回報{id: catId, size: 'large'},但編號即使是在我的資料庫中記錄的貓種ID不回傳的品種。
我是 typeorm 的新手,我認為 ManyToOne 所做的一件事就是建立 FK 約束。為什么查詢行為是這樣的,我怎樣才能在不使用連接的情況下回傳物種 ID?
uj5u.com熱心網友回復:
在您的情況下,我認為您在Cat物體中缺少 1 個額外的列。您將存盤的列species_id,或者如果您希望使其準確,請使用單數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;
}
您可以在 typeorm 檔案中找到更多資訊:https ://typeorm.io/#/many-to-one-one-to-many-relations
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341487.html
標籤:PostgreSQL 打字机
