【发布时间】:2021-08-04 15:46:15
【问题描述】:
我正在将 typeorm 与 NestJs 一起使用,我尝试加入 3 个关系但收到错误 path comment.user in entity was not found
这是我的表用户
| Id | username |
|---|---|
| 1 | row |
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@OneToMany(() => PostEntity, (post) => post.user, { eager: true })
posts: PostEntity[];
这是我的表帖
| Id | desc | user_id |
|---|---|---|
| 1 | text | 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[];
这是我的餐桌评论
| Id | comment | user_id | postId |
|---|---|---|---|
| 1 | comment post 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']
还是不行
【问题讨论】:
标签: mysql express nestjs typeorm