gpt4 book ai didi

javascript - 找不到别名。也许你忘了加入它

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:47 24 4
gpt4 key购买 nike

在我的 nectjs 项目中,我使用的是 TypeORM,我有 2 个实体用户和帖子,我想在他们之间建立关系

用户.entity.ts

@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column({ length: 50, unique: true })
name: string;

@OneToMany(type => Post, post => post.user)
posts: Post[];
}

post.entity.ts

@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?

最佳答案

你必须先注入(inject)Repository:

constructor(
@InjectRepository(Post) private readonly postRepository: Repository<Post>
) {
}

然后您可以通过传入别名为 Post 实体创建 QueryBuilder:

this.postRepository.createQueryBuilder('post')
// ^^^^^^^^^^^^^^^^
.leftJoinAndSelect(
'post.user',
'user',
'post.title = :title',
{ title: 'title1' },
)
.where('user.id = :id', { id })
.getOne();

关于javascript - 找不到别名。也许你忘了加入它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54668910/

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