返回post
数据时如何获得user
类别?
实体:
@Entity()
export class Category extends BaseEntity {
@PrimaryGeneratedColumn()
id: string;
@Column()
name: string;
@Column()
description: string;
}
@Entity()
export class Posts extends BaseEntity {
@PrimaryGeneratedColumn()
id: string;
@Column()
title: string;
@Column()
content: string;
@ManyToMany(() => Category, (category) => category.id, [
"insert",
"update",
"remove",
])
@JoinColumn({ name: "post_categories" })
categories: Category[];
}
@Entity("users")
export class User extends BaseEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({ unique: true })
email: string;
@ManyToMany(() => Posts)
@JoinColumn()
posts: Post;
}
查询:
await this.userRepository.findOne({
where: { id }
});
这只会返回带有帖子但没有类别的用户模型:
{
id: 1,
email: 'foo@bar.com',
posts: [
{id: 1, title: 'test', content: 'lorem ipsum...'},
{id: 1, title: 'test', content: 'lorem ipsum...'},
{id: 1, title: 'test', content: 'lorem ipsum...'},
]
}
答案 0 :(得分:0)
您需要给findOne
一个relations
数组。试试
await this.userRepository.findOne(id, { relations: ["categories"] });