gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:46:53 24 4
gpt4 key购买 nike

@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 个实体,我想进行查询以获取用户的所有帖子,并为该帖子获取所有图像。我正在尝试使用以下代码执行此操作:
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")


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

最佳答案

我自己也一直在努力解决同样的问题。

您应该在此处更改关系:

@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() 装饰器,因为它们在一对多和多对一关系中不是必需的,您可以在官方文档中看到它:

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有关这方面的更多详细信息,您还将找到此类关系的示例。

关于nestjs - TypeORM:当我们有一对多和多对一关系时加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com