티스토리 뷰

관련 entity

// hashtag.entity.ts
@Entity()
export class Hashtag {
    @ApiProperty({ description: '인덱스' })
    @PrimaryGeneratedColumn({
        type: 'int',
        name: 'id'
    })
    id: number;

    @ApiProperty({ description: '해시태그 키워드' })
    @IsString()
    @Column('varchar', {
        name: 'keyword',
        nullable: false,
        length: 30
    })
    keyword: string

    @ApiProperty({ description: '게시글 리스트' })
    @IsNumber()
    @ManyToMany((type) => PostEntity, (post) => post.hashtags)
    @JoinTable({
        name: 'hashtag_post'
    })
    posts: PostEntity[]
}
// post.entity.ts
@Entity()
export class PostEntity {
    @ApiProperty({ description: '인덱스' })
    @PrimaryGeneratedColumn({
        type: 'int',
        name: 'id'
    })
    id: number;

    @ApiProperty({ description: '게시글 내용' })
    @IsString()
    @Column('varchar', {
        name: 'content',
        nullable: true,
        length: 2000
    })
    content?: string;

    @ApiProperty({ description: '게시글 등록일' })
    @CreateDateColumn({})
    createdAt: string;

    @ApiProperty({ description: '게시글 작성자' })
    @IsNumber()
    @ManyToOne((type) => User, (user) => user.posts, {eager: true})
    writer: User;

    @ApiProperty({ description: '댓글 리스트' })
    @IsArray()
    @OneToMany((type) => Comment, (comment) => comment.post)
    comments?: Comment[]

    @ApiProperty({ description: '해시태그 리스트' })
    @IsArray()
    @ManyToMany((type) => Hashtag, (hashtag) => hashtag.posts)
    hashtags: Hashtag[]

    @ApiProperty({ description: '좋아요 누른 유저 리스트' })
    @IsArray()
    @ManyToMany((type) => User, (user) => user.likes)
    likers?: User;
}

 


사용한 문법 정리

- 해시태그별 모든 게시글 불러오기

await this.hashtagRepository.findOne({
    where: {
        id: hashtagId
    },
    relations: ['posts']
})

 

- 키워드에 해당하는 해시태그 id 조회

await this.hashtagRepository.findOne({
    select: ['id'],
    where: { keyword }
})

 

- 해시태그 추가

await this.hashtagRepository
    .createQueryBuilder()
    .insert()
    .into(Hashtag)
    .values({ keyword })
    .execute()

 

- 해시태그 id와 게시글 id가 일치하는 row 조회

await this.hashtagRepository
    .createQueryBuilder('hashtag')
    .leftJoinAndSelect('hashtag.posts', 'posts')
    .where(`hashtag.id = ${hashtagId.id}`)
    .andWhere(`posts.id = ${postId}`)
    .getOne()

- leftJoinAndSelectandWhere을 처음 알았다

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함