在我的nectjs项目中,我正在使用TypeORM,并且我有2个实体user和post, 我想在他们之间建立联系
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 50, unique: true })
name: string;
@OneToMany(type => Post, post => post.user)
posts: Post[];
}
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 30 })
title: string;
@ManyToOne(type => User, user => user.posts)
user: User;
}
所以我想加入这些表并按特定用户的标题获取帖子
const PostObject = await createQueryBuilder("post")
.leftJoinAndSelect(
"post.user",
"user",
"post.title = :title",
{ title: "title1" }
)
.where("user.id = :id", { id: id })
.getOne();
但是当我运行项目并执行此功能时,出现此错误:
Error: "post" alias was not found. Maybe you forget to join it?
答案 0 :(得分:1)
您必须先注入Repository
:
constructor(
@InjectRepository(Post) private readonly postRepository: Repository<Post>
) {
}
然后,您可以通过传入别名为QueryBuilder
实体创建Post
:
this.postRepository.createQueryBuilder('post')
.leftJoinAndSelect(
'post.user',
'user',
'post.title = :title',
{ title: 'title1' },
)
.where('user.id = :id', { id })
.getOne();
答案 1 :(得分:0)
也可以像下面那样使用 getRepository。
const PostObject = await getRepository("post").createQueryBuilder("post")
.leftJoinAndSelect(
"post.user",
"user",
"post.title = :title",
{ title: "title1" }
)
.where("user.id = :id", { id: id })
.getOne();