Reputation: 2063
I wanted to create a one-to-many relation in TypeORM with a field other than id, the usual relation looks like this, but in the same example, lets say for instance the User
table's column name
was also unique, now I want to reference that in the relation, which then the foreign key in photos would contain value of name
and give it a different column name in Photos
table other than userId
to be e.g. userName
, how exactly would i do that, am stuck and frankly hove no idea how to proceed.
Upvotes: 3
Views: 2058
Reputation: 353
If you want your relation to point to a column other than id
, you must add referencedColumnName: '<column name here>'
to your @JoinColumn()
options.
e.g:
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column()
url: string;
@ManyToOne(() => User, user => user.photos)
@JoinColumn({ name: 'userName', referencedColumnName: 'name' })
user: User;
}
Also, be careful of specifying the referencedColumnName from typeORM's point of view, not the real underlying driver column name.
For example, if you want to reference a column named user_name
, but your entity's property uses camelCase userName
, you must specify:
referencedColumnName: 'userName'
if you specify the database column name instead, you will get errors complaining that typeORM could not find the referenced column in your entity definition.
Upvotes: 2
Reputation: 275
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column()
url: string;
@ManyToOne(() => User, user => user.photos)
@JoinColumn({ name: 'userName' }) // < -- add this line
user: User;
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Photo, photo => photo.user)
photos: Photo[];
}
Upvotes: 1