在下面的示例中,
BlogPost
实体依赖于BlogPostCategory
:
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne as ManyToOne, Relation } from "typeorm";
import { isUndefined } from "@yamato-daiwa/es-extensions";
@Entity()
export default class BlogPost {
@PrimaryGeneratedColumn("uuid")
public readonly ID!: BlogPost.ID;
@Column({ type: "varchar", nullable: false })
public readonly heading!: string;
@Column({ type: "text", nullable: false })
public readonly HTML!: string;
/* [ Theory ] About `Relation` https://stackoverflow.com/a/71983552/4818123 */
@ManyToOne(
(): typeof BlogPostCategory => BlogPostCategory,
(blogPostCategory: BlogPostCategory): ReadonlyArray<BlogPost> => blogPostCategory.blogPosts
)
public readonly category!: Relation<BlogPostCategory>;
@Column({ type: "varchar", nullable: false })
public readonly metaDescription!: string;
@Column({ type: "timestamp with time zone", nullable: false })
public readonly publishingDateTime__ISO8601!: string;
public constructor(
properties?: Readonly<Omit<BlogPost, "ID">>
) {
if (isUndefined(properties)) {
return;
}
this.heading = properties.heading;
this.HTML = properties.HTML;
this.category = properties.category;
this.metaDescription = properties.metaDescription;
this.publishingDateTime__ISO8601 = properties.publishingDateTime__ISO8601;
}
}
@Entity()
@Unique([ "text" ])
export default class BlogPostCategory {
@PrimaryGeneratedColumn("uuid")
public readonly ID!: BlogPostCategory.ID;
@Column({ type: "varchar", nullable: false })
public text!: string;
@OneToMany(
(): typeof BlogPost => BlogPost,
(blogPost: BlogPost): BlogPostCategory => blogPost.category
)
public blogPosts!: Array<BlogPost>;
public constructor(properties?: Readonly<Omit<BlogPostCategory, "ID">>) {
if (isUndefined(properties)) {
return;
}
this.text = properties.text;
}
}
如何知道有多少帖子属于特定类别?
在
await this.blogPostCategoryRepository.find({ relations: [ "blogPosts" ] });
所有博客文章都将被检索到每个类别,这对性能影响巨大。 目标是知道每个类别有多少博客文章,但所有博客文章的检索都是主动提供的。
你应该在 findOption 中添加 loadRelationIds: true ,它将返回 id 数组
await this.blogPostCategoryRepository.find({
loadRelationIds: true,
relations: ['blogPosts'],
});