// TagModel
@ManyToMany(() => PostModel, (post) => post.tags)
posts: PostModel[];

// PostModel
@ManyToMany(() => TagModel, (tag) => tag.posts)
tags: TagModel[];

Many to Many는 어느 한곳에다가 Jointable을 넣어줘야한다. (애노테이션)


//PostModel
@ManyToMany(() => TagModel, (tag) => tag.posts)
  @JoinTable()
  tags: TagModel[];

Untitled

Tag Posts 만들기

@Post('posts/tags')
  async createPostsTags() {
    const post1 = await this.postRepository.save({
      title: 'Next.js Lecture',
    });

    const post2 = await this.postRepository.save({
      title: 'Programming Lecture',
    });

    const tag1 = await this.tagRepository.save({
      name: 'javascript',
      posts: [post1, post2],
    });

    // Tag에 post 넣기
    const tag2 = await this.tagRepository.save({
      name: 'Typescript',
      posts: [post1],
    });

    // Post에 tag 넣기
    const post3 = await this.postRepository.save({
      title: 'NestJS Lecture',
      tags: [tag1, tag2],
    });
    console.log(post3);

    return true;
  }
{
        "id": 3,
        "title": "Next.js Lecture",
        "tags": [
            {
                "id": 1,
                "name": "javascript"
            },
            {
                "id": 2,
                "name": "Typescript"
            }
        ]
    },
    {
        "id": 4,
        "title": "Programming Lecture",
        "tags": [
            {
                "id": 1,
                "name": "javascript"
            }
        ]
    },
    {
        "id": 5,
        "title": "NestJS Lecture",
        "tags": [
            {
                "id": 1,
                "name": "javascript"
            },
            {
                "id": 2,
                "name": "Typescript"
            }
        ]
    },
{
        "id": 1,
        "name": "javascript",
        "posts": [
            {
                "id": 3,
                "title": "Next.js Lecture"
            },
            {
                "id": 4,
                "title": "Programming Lecture"
            },
            {
                "id": 5,
                "title": "NestJS Lecture"
            }
        ]
    },
    {
        "id": 2,
        "name": "Typescript",
        "posts": [
            {
                "id": 3,
                "title": "Next.js Lecture"
            },
            {
                "id": 5,
                "title": "NestJS Lecture"
            }
        ]
    }