티스토리 뷰
관련 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()
- leftJoinAndSelect와 andWhere을 처음 알았다
'라이브러리, 프레임워크 > TypeORM' 카테고리의 다른 글
[TypeORM + NestJS] 조회수 증가 쿼리 예시(기존 컬럼 값 +1) (0) | 2022.07.01 |
---|---|
[TypeORM] onDelete 옵션 정리, 예시 (0) | 2022.06.27 |
[TypeORM + NestJS] 해시태그별 게시글 불러오기 - ManyToMany relations 조건별 조회 (0) | 2022.06.15 |
[TypeORM + NestJS] 해시태그 추가 api 구현 (0) | 2022.06.14 |
[TypeORM + NestJS] 다대다(ManyToMany) 테이블 생성 - JoinTable (0) | 2022.06.13 |
댓글