TypeORM Nested Relation

00_8_3·2021년 4월 14일
0

하려는 것

  • user_profile.entity.ts
  • user.entity.ts
  • post.entity.ts

user_profile과 user 엔티티는 1:1 관계

user과 post 엔티티는 1:다 관계

user_profile -> user -> post

유저가 게시글 작성 할 때마다 user_profilepost_count가 증가

user_profile에서 user.posts를 가져오려고
@Afterload를 사용 하려함

@Afterload

  • user_profile.entity.ts
    에서
@Column()
post_count: number;

@OneToOne((type) => User, (user) => user.profile, { onDelete: 'CASCADE' })
user: User;

@Afterload()
updatePostCount() {
  // 
	this.post_count = this.user.posts.length
}

user.service.ts에서
userProfileRepository를 사용하면this.user.posts 출력 잘됨
userRepository를 사용하면 출력이 안됨

출력이 잘되도 this.post_count = this.user.posts.length를 이용해서 저장이 안됨

임시방편

post를 새로 만들 때
user.profile.post_count += 1
직접 저장

0개의 댓글