더북(TheBook)

이 코드에 대한 설명을 정리했다.

1. GormController를 임베디드 필드로 지정

2. Order 메서드와 Find 메서드로 전체 포스트 조회

3. First 메서드로 id에 해당하는 포스트 조회

c.Txn.Where(&models.Comment{PostId: id}).Find(&post.Comments)를 통해 연관된 댓글도 조회한다.

4. Save 메서드로 포스트 수정

5. Create 메서드로 포스트 생성

6. Delete 메서드로 포스트 삭제

c.Txn.Where("post_id = ?", id).Delete(&models.Comment{})를 통해 연관된 댓글도 삭제한다.

코멘트 컨트롤러에서도 gorm으로 데이터를 처리하도록 코드를 수정해 보자. app/controllers/comment.go 파일을 다음과 같이 수정한다.

▼ app/controllers/post.go

package controllers
 
import (
    “goblog/app/models”
    “goblog/app/routes”
 
“github.com/revel/revel” ) type Comment struct { GormController } func (c Comment) Create(postId int, body, commenter string) revel.Result { comment := models.Comment{PostId: postId, Body: body, Commenter: commenter} c.Txn.Create(&comment) c.Flash.Success(“댓글 작성 완료”) return c.Redirect(routes.Post.Show(postId)) } func (c Comment) Destroy(postId, id int) revel.Result { c.Txn.Where(“id = ?”, id).Delete(&models.Comment{}) c.Flash.Success(“댓글 삭제 완료”) return c.Redirect(routes.Post.Show(postId)) }

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.