TypeORM 外键未显示在查找调用中

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,
  ...
 }
]

我正在尝试获取我的 Contact 中包含的所有列,但我只能获取与其他实体没有任何关系的列。 它不包括 user_id 列。例如为什么不能获取外键?

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;
  ...
}

您应该显式添加 userId 列并将该列名称传递给 @JoinColumn 装饰器。

希望对您有所帮助。

这里是关于它的讨论。 https://github.com/typeorm/typeorm/issues/586#issuecomment-311282863

您可以设置eager: true以便使用查找命令加载用户

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

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