[英]How do I add a `relation` to my PostgresQL database using Typeorm?
For example例如
@Entity()
class Post {
@Column()
post_hash: string;
@Column()
title: string;
categorys: Array<Category> = [];
}
@Entity()
class Category {
@Column()
content: string;
@Column()
post_hash: number;
}
I want to query all the category
content of the corresponding post
through Typeorm.我想通过Typeorm查询对应
post
所有category
内容。
I tried this method and failed.我试过这个方法,失败了。
this.createQueryBuilder('Post').leftJoinAndMapOne(
'Post.categorys',
Category,
'category',
'category.post_hash = post.post_hash'
)
This is my error message.这是我的错误信息。
QueryFailedError: relation "post" does not exist
First of all, you must identify each row with a unique ID using @PrimaryColumn()
or@PrimaryGeneratedColumn()
decorators.首先,您必须使用
@PrimaryColumn()
或@PrimaryGeneratedColumn()
装饰器来标识具有唯一ID 的每一行。
Each Post
entity can have multiple categories and each Category
entity is related to multiple posts .每个
Post
实体可以有多个类别,并且每个Category
实体与多个职位。 This is called a many-to-many relation and must be correctly mapped using the @ManyToMany()
decorator.这称为多对多关系,必须使用
@ManyToMany()
装饰器正确映射。 See this for more information.有关更多信息,请参阅此内容。
@Entity()
class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
post_hash: string;
@Column()
title: string;
@ManyToMany(() => Category, category => category.posts)
@JoinTable()
categories: Category[];
}
@Entity()
class Category {
@PrimaryGeneratedColumn()
id: number;
@Column()
content: string;
@Column()
post_hash: number;
@ManyToMany(() => Post, post => post.categories)
posts: Post[];
}
Obtain all Post
(s) with the related categories .获取所有具有相关类别的
Post
。
const posts: Post[] = await getRepository(Post)
.find({ relations: ['categories'] });
Using QueryBuilder
:使用
QueryBuilder
:
const posts: Post[] = await getRepository(Post)
.createQueryBuilder('post')
.leftJoinAndSelect('post.categories', 'category')
.getMany();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.