【发布时间】:2021-10-18 08:29:19
【问题描述】:
我正在尝试在 Posts 和 Hashtags 之间建立关系,这是我的两个实体,
@Entity('posts')
export class Posts {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 200, nullable: true })
caption: string;
@ManyToMany(() => Hashtags, (hashtags) => hashtags.posts, { eager: true })
@JoinTable({ name: 'posts_hashtags_relation' })
hashtags: Hashtags[];
@ManyToOne(() => User)
@JoinColumn({ name: 'author_id' })
author: User;
}
@Entity('hashtags')
export class Hashtags {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
hashtag: string;
@ManyToMany(() => Posts, (post) => post.hashtags, {
eager: false,
cascade: true,
})
posts: Posts[];
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
}
通过这些,typeorm 创建了一个数据库posts_hashtags_relation,其中包含postsId 和hashtagsId 列
我在主题标签表中保存主题标签的服务是这样的
async createPost(creator : User, body: CreatePostDto) {
if (!body.caption) {
throw new BadRequestException('Post must contain some text');
}
// Extract hashtags from the post caption body
const hashtags = body.caption.match(/\#\w+/g); // hashtags are the array of all hashtags in the post caption
if(hashtags){
for (const hashtag of hashtags) {
const hashtagEntity = await this.hashtagRepo.findOne({ hashtag });
if (!hashtagEntity) {
await this.hashtagRepo.save({ hashtag });
}
}
}
const post = new Posts();
post.author = creator;
post.caption = body.caption;
post.images = body.images;
const resPost = await this.postsRepo.save(post);
return resPost;
}
但是如何保存posts_hashtags_relation表中的关系呢?
【问题讨论】:
标签: database orm nestjs typeorm