@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;
}
Run Code Online (Sandbox Code Playgroud)
我有这3个实体,我想查询一个用户的所有帖子,并让该帖子获取所有图像。我正在尝试使用以下代码执行此操作:
return await this.postRepository.createQueryBuilder("post")
.innerJoinAndSelect("post.images", "image")
.where("user_id = :userId", {userId: id})
.getMany();
Run Code Online (Sandbox Code Playgroud)
我得到以下错误:
"Cannot read property 'joinColumns' of undefined"
Run Code Online (Sandbox Code Playgroud)
我还尝试了此方法,而不是上面的innerJoin:
.innerJoinAndSelect(Image, "image", "image.post_id = post.id")
Run Code Online (Sandbox Code Playgroud)
这样,我不再收到该错误,但是结果是我仅收到该帖子,而没有从中获取图像
小智 10
@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;
}
Run Code Online (Sandbox Code Playgroud)
尝试这个
我自己一直在为同样的问题而苦苦挣扎。
您应该在此处更改关系:
@OneToMany(type => Image, image => image.id)
images: Image[];
Run Code Online (Sandbox Code Playgroud)
对此:
@OneToMany(type => Image, image => image.post)
images: Image[];
Run Code Online (Sandbox Code Playgroud)
请注意,image.id应该是image.post,以匹配反面。
*编辑=>在这里出现同样的问题:
@OneToMany(type => Post, post => post.id)
posts: Post[];
Run Code Online (Sandbox Code Playgroud)
此关系也应具有相反的一面, post.id应该是post.user:
@OneToMany(type => Post, post => post.user)
posts: Post[];
Run Code Online (Sandbox Code Playgroud)
请注意这一点,因为它直到运行时才会引发任何错误。
我刚刚使用上述修改测试了此查询,但错误消失了:
return await this.postRepository.find({
relations: ['images', 'user'],
where: { user: { id: id } },
});
Run Code Online (Sandbox Code Playgroud)
您也可以省略@JoinColumn()装饰,因为他们没有必要在一对多和多对一的关系,你可以看到它在官方文件中提到:
您可以在@ManyToOne / @OneToMany关系中省略@JoinColumn。没有@ ManyToOne,@ OneToMany无法存在。如果要使用@OneToMany,则需要@ManyToOne。在设置@ManyToOne的位置-它的相关实体将具有“关系ID”和外键。
有关更多详细信息,请参考TypeORM文档,您还将找到这种类型的关系的示例。
| 归档时间: |
|
| 查看次数: |
7544 次 |
| 最近记录: |