【发布时间】:2021-03-05 13:42:54
【问题描述】:
我实际上是通过创建带有文章 ID 和标签 ID 的关系表来创建带有关联标签的文章系统。
问题是关系是为第一个标签而不是其他标签完成的,我不知道如何做到这一点。
首先,我在文章创建 DTO 中将标签作为数组接收
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
export class CreateArticleDto {
@ApiProperty()
@IsNotEmpty()
title: string;
@ApiProperty()
@IsNotEmpty()
content: string;
@ApiProperty()
author: string;
@ApiProperty()
tags: Array<number>;
@ApiProperty({ type: 'string', format: 'binary' })
image: string;
}
然后,我在文章模块中创建关系
@ManyToMany(() => TagsEntity)
@JoinTable({
name: 'article_tags',
joinColumn: {
name: 'articleId',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'tagId',
referencedColumnName: 'id',
},
})
tags: TagsEntity[];
另外,这里是我创建文章时的文章服务
async createArticle(articleDto: CreateArticleDto) {
const readingTime = Utils.estimateReadingTime(articleDto.content);
const slug: string = Utils.slugify(articleDto.title);
const tags: TagsEntity[] = await this.tagsRepository.findByIds(articleDto.tags);
const articleEntity: ArticlesEntity = await this.articlesRepository.create({
...articleDto,
readingTime,
tags,
slug,
});
return this.articlesRepository.save(articleEntity);
}
结果是,如果我尝试创建具有 3 个标签(id 1、id 2、id 3)的文章,则只有标签 ID 1 的文章 ID 1 而不是标签 ID 2 和 3 而不是文章 ID 1 与每个标签 ID 对应 3 次。
【问题讨论】:
-
可以分享一下服务的代码吗?你如何存储带有标签的文章?
-
我把它添加到帖子@Youba
-
您的代码似乎可以正常工作,我担心标签数组不是从源头获取的,您能告诉我后端从前端或邮递员那里得到的数组格式吗?跨度>
-
我通过发送与现有标签相对应的 ID(数字)数组来使用 swagger
-
你能登录
articleDto.tags并分享结果吗?
标签: sql relationship nestjs typeorm