I'm actually creating an article system with associated tags by creating a relation table with the article ID and the tag ID.
The problem is that the relation is done for the first tag and not for the others and I have no idea of how to do this.
First, I'm receiving the tags as an array in the articles create 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;
}
Then, I create the relation in the articles module
@ManyToMany(() => TagsEntity)
@JoinTable({
name: 'article_tags',
joinColumn: {
name: 'articleId',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'tagId',
referencedColumnName: 'id',
},
})
tags: TagsEntity[];
Moreover, here is my service for articles when I create the article
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);
}
The result is that if I try to create an article with 3 tags (id 1, id 2, id 3), there is only the article ID 1 with the tag ID 1 and not the tag ID 2 and 3 instead of having the article ID 1 three times with each tag ID.
Till you can share the code of your service, I've tried with the same entities and DTo you've used and I added all the tags without any problem: here is my create function :
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);
}
UPDATE
After you comment, the problem is in the format fo the array you send to the Ws I think you're sending the array this way [tags]: 1,2,3
Instead, the way you should to send the array is:
tags[] : 1
tags[] : 2
tags[] : 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.