【问题标题】:Relation for articles and tags with TypeORM in NestJSNestJS 中文章和标签与 TypeORM 的关系
【发布时间】: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


【解决方案1】:

在您可以共享服务代码之前,我已经尝试过使用相同的实体和 DTo,并且我添加了所有标签没有任何问题:这是我的创建功能:

async  create(createArticleDto: CreateArticleDto) {
 const article = new Article();
 article.title = createArticleDto.title;
 ...
 const tags: Tag[] = await this.tagRepository.findByIds(createArticleDto.tags);
   article.tags = tags;
return await this.articleRepository.save(article);

}

更新

在您发表评论后,问题在于您发送给 Ws 的数组的格式 我认为您以这种方式发送数组 [tags]: 1,2,3

相反,您应该发送数组的方式是:

tags[] : 1
tags[] : 2
tags[] : 4

【讨论】:

  • 我需要发送一个包含所有 ID 的唯一数组,而不是包含 ID 的对象数组
  • 很高兴为您工作,感谢您接受此答案
  • 这不起作用,你给了我一个包含 ID 的对象数组的解决方案,但我需要将 ID 数组作为数字 (int) 发送
  • 我认为您不理解语法,正如您在此处看到的 tags[] : 1 tags[] : 2 tags[] : 4 这只是发送我发送给测试的简单数组的一种方式,这完全是关于语法
  • 是的,这是一种发送数组的方式,但我需要以这种方式发送数组 [tags]: 1,2,3 就像 Swagger 在定义 Array 类型时所做的那样
猜你喜欢
  • 2022-01-02
  • 2020-03-21
  • 2021-03-06
  • 2020-09-01
  • 2022-01-02
  • 1970-01-01
  • 2020-12-09
  • 2021-04-23
  • 1970-01-01
相关资源
最近更新 更多