我正在使用NestJs中的typeorm,并尝试连接3个关系,但出现了错误实体中路径comment.user未找到
以下是我的User表格
Id | 用户名 |
---|---|
1 | row |
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@OneToMany(() => PostEntity, (post) => post.user, { eager: true })
posts: PostEntity[];
这是我的表格 "Posts"
Id | 描述 | 用户ID |
---|---|---|
1 | 文本 | 1 |
@PrimaryGeneratedColumn()
id: number;
@Column()
desc: string;
@Column()
userId: number;
@ManyToOne(() => User, (user) => user.posts, {
eager: false,
onDelete: 'CASCADE',
})
user: User[];
@OneToMany(() => CommentEntity, (comment: CommentEntity) => comment.post, {
eager: true,
onDelete: 'CASCADE',
})
comment: CommentEntity[];
这是我的表格注释
编号 | 评论 | 用户编号 | 文章编号 |
---|---|---|---|
1 | 对文章 1 进行评论 | 1 | 1 |
@PrimaryGeneratedColumn()
id: number;
@Column()
comment: string;
@Column()
userId: number;
@Column()
postId: number;
@ManyToOne(() => PostEntity, () => (post: PostEntity) => post.comment, {
eager: false,
onDelete: 'CASCADE',
})
post: PostEntity[];
@OneToOne(() => User)
@JoinColumn()
user: User;
在这里我使用OneToOne,因为1个评论只能由1个用户评论
这是我的数据样式
```
this.createQueryBuilder('post')
.leftJoinAndSelect('post.user', 'user')
.leftJoinAndSelect('post.comment', 'comment')
.select(['post', 'user.id', 'user.username', 'comment'])
.getMany();
```
这是我得到的内容
[
{
id: 1,
description: 'comment post 1',
userId: 1,
user: {
id: 1,
username: 'row',
},
comment: [
{
id: 1,
description: 'comment',
userId: 1,
postId: 1,
},
],
},
];
在评论中,我想要将userId与发表评论的用户关联起来。我希望数据长这样:
[
{
id: 1,
description: 'comment post 1',
userId: 1,
user: {
id: 1,
username: 'row',
},
comment: [
{
id: 1,
description: 'comment',
userId: 1,
postId: 1,
user: {
// if different user comment will show different username
id: 1,
username: 'row',
},
},
],
},
];
这是我尝试做的事情
this.createQueryBuilder('post')
.leftJoinAndSelect('post.user', 'user')
.leftJoinAndSelect('post.comment', 'comment')
.leftJoinAndSelect('post.comment.user', 'user')
.select(['post', 'user.id', 'user.username', 'comment'])
.orderBy('post.updated_at', 'DESC')
.getMany();
.leftJoinAndSelect('post.comment.user', 'user') // In this line I want to join userId but Its show an error path comment.user in entity was not found
更新
我试图使用这个(指的是PostEntity)。
this.find({ relations: ['user', 'comment', 'comment.user']
但仍然无法正常工作。
commentedUser
你不需要做任何事情,它只是一个别名) - Eranga Heshan