TypeORM:当我们有一对多和多对一关系时加入

TypeORM: Joining when we have one to many and many to one relationship

@Entity()
export class User {
  @PrimaryColumn()
  id: string;

  @Column({unique: true})
  username: string;

  @Column({unique: true})
  email: string;

  @OneToMany(type => Post, post => post.id)
  posts: Post[];
}

@Entity()
export class Post {

  @PrimaryGeneratedColumn()
  id: number;

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

  @OneToMany(type => Image, image => image.id)
  images: Image[];
}
 
@Entity()
export class Image {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(type => Post, post => post.images)
  @JoinColumn({name : 'post_id'})
  post: Post;
}

我有这 3 个实体,我想查询一个用户的所有 post,然后 post 获取所有图像。我正在尝试使用以下代码执行此操作:

return await this.postRepository.createQueryBuilder("post")
  .innerJoinAndSelect("post.images", "image")
  .where("user_id = :userId", {userId: id})
  .getMany();

我收到以下错误:

Cannot read property 'joinColumns' of undefined

我也试过这个而不是上面的.innerJoin

.innerJoinAndSelect(Image, "image", "image.post_id = post.id")

这样我就不会再收到那个错误了,但结果我只得到了 post 而我没有从中得到图像

@Entity()
export class User {

 @OneToMany(type => Post, post => post.user)
 posts: Post[];
}

@Entity()
export class Post {

 @PrimaryGeneratedColumn()
 id: number;

 @Column()
 user_id: number;

 @ManyToOne(type => User)
 @JoinColumn({name: 'user_id', referencedColumnName: 'id'})
 user: User;

 @OneToMany(type => Image, image => image.post)
 images: Image[];
}

@Entity()
export class Image {
 @PrimaryGeneratedColumn()
 id: number;

 @Column()
 post_id: number;

 @ManyToOne(type => Post)
 @JoinColumn({name : 'post_id', referencedColumnName: 'id'})
 post: Post;
}

试试这个

我自己也一直在为同样的问题而苦苦挣扎。

你应该改变这里的关系:

@OneToMany(type => Image, image => image.id)
images: Image[];

为此:

@OneToMany(type => Image, image => image.post)
images: Image[];

注意image.id应该是image.post而不是匹配反面

*编辑=> 在这里出现同样的问题:

@OneToMany(type => Post, post => post.id)
posts: Post[];

这个关系应该也有相反的一面,post.id应该是post.user而不是:

@OneToMany(type => Post, post => post.user)
posts: Post[];

注意这一点,因为它直到运行时才抛出任何错误。

我刚刚用上述修改测试了这个查询,错误消失了:

return await this.postRepository.find({
  relations: ['images', 'user'],
  where: { user: { id: id } },
});

您也可以省略 @JoinColumn() 装饰器,因为它们在 one to many多对一关系,可以看官方文档中提到:

You can omit @JoinColumn in a @ManyToOne / @OneToMany relation. @OneToMany cannot exist without @ManyToOne. If you want to use @OneToMany, @ManyToOne is required. Where you set @ManyToOne - its related entity will have "relation id" and foreign key.

请参阅 TypeORM documentation 了解更多详细信息,您还将找到此类关系的示例。