Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM foreign key not showing on a find call

export class Contact extends BaseEntity {
  ...
  @ManyToOne(() => User, { nullable: false })
  @JoinColumn({ name: 'user_id' })
  user: User;
  ...
}

const repo = new Repository<User> ();
const response = await repo.findAll();
console.log(response);

console.log:
[
 Contact {
  id: 1,
  ...
 },
 Contact {
  id: 2,
  ...
 }
]

I am trying to fetch all the columns included on my Contact, but I only able to fetch the columns that does not have any relationship from the other entity. It does not include user_id columns. Why can't to get foreign key for instance?

like image 469
tmpacifitech Avatar asked Jun 18 '20 22:06

tmpacifitech


2 Answers

export class Contact extends BaseEntity {
  ...
  // add column explicitly here
  @Column({ name: 'user_id' })
  userId: number;

  @ManyToOne(() => User, { nullable: false })
  @JoinColumn({ name: 'user_id' })
  user: User;
  ...
}

You should add userId column explicitly and pass this column name to @JoinColumn decorator.

Hope it helps.

Here is discussion about it. https://github.com/typeorm/typeorm/issues/586#issuecomment-311282863

like image 116
xyingsoft Avatar answered Nov 07 '22 01:11

xyingsoft


You can set eager: true in order to load User with the find command

 @ManyToOne(() => User, { nullable: false, eager: true })
  @JoinColumn({ name: 'user_id' })
  user: User;

Link: https://orkhan.gitbook.io/typeorm/docs/relations

like image 41
Green3rd Avatar answered Nov 07 '22 00:11

Green3rd