golang
[gorm] 다형성 관계
bkdragon
2024. 9. 11. 22:33
gorm 에는 다형성 관계라고 하는 아주 막강한 기능을 제공한다.
공지사항과 게시글이 있다. 공지사항과 게시글에는 댓글을 달 수 있다. 이럴 때 보통 4개의 테이블을 만들게 된다.
- Notice
- Board
- Notice_Comment
- Board_Comment
gorm 에선 다형성 관계를 통해 하나의 Comment 테이블로 해결할 수 있다!
type Comment struct {
gorm.Model
Content string
WriterID uint
Writer User
OwnerID int // 연관된 모델 ID
OwnerType string // 연괸된 모델의 테이블 명이 들어간다.
}
Comment 모델에 OwnerID 와 OwnerType을 추가하자. Owner 라는 이름은 그냥 적당히 지은 것이다.
type Board struct {
gorm.Model
Title string
Content string
WriterID uint
Writer User
LikeCount int
Comments []Comment `gorm:"polymorphic:Owner;"`
}
type Notice struct {
gorm.Model
Title string
Content string
WriterID uint
Writer User
Type string
ViewCount int
Comments []Comment `gorm:"polymorphic:Owner;"`
}
gorm 태그의 polymorphic:Owner 옵션을 를 통해 다형성 관계를 설정할 수 있다.
Board에 Comment를 추가할 때
comment := models.Comment{
WriterID: request.UserID,
Title : request.Title,
Content: request.Content,
Type : "basic",
}
db.Model(&Board{}).Where("id = ?", id).Association("Comments").Append(&comment)
이렇게 하게 되면 OwnerID 가 Board 의 pk 가 되고 OwnerType 이 테이블 명이 된다 gorm은 자동으로 복수형으로 변환해주기 때문에 boards가 저장된다. Notice도 마찬가지!
gorm 의 다형성 관계는 여러 모델이 공통된 테이블(예: Comment
)과 관계를 맺을 때 매우 유용하다. 불필요한 테이블도 줄이고 귀찮음도 줄 일 수 있다.