더북(TheBook)

10.6.2 gorm으로 데이터 처리

다음으로는 컨트롤러에서 네이티브 쿼리(native query)로 처리하던 작업을 ORM 방식으로 처리하도록 코드를 변경해 보자.

app/controllers/post.go 파일을 다음과 같이 수정한다.

▼ app/controllers/post.go

package controllers
 
import (
    “goblog/app/models”
    “goblog/app/routes”
 
“github.com/revel/revel” ) // ➊ GormController를 임베디드 필드로 지정 type Post struct { GormController } // ➋ Order 메서드와 Find 메서드로 전체 포스트 조회 func (c Post) Index() revel.Result { var posts []models.Post c.Txn.Order(“created_at desc”).Find(&posts) return c.Render(posts) } // ➌ First 메서드로 id에 해당하는 포스트 조회 func (c Post) Show(id int) revel.Result { var post models.Post c.Txn.First(&post, id) c.Txn.Where(&models.Comment{PostId: id}).Find(&post.Comments) return c.Render(post) } // ➍ Save 메서드로 포스트 수정 func (c Post) Update(id int, title, body string) revel.Result { var post models.Post c.Txn.First(&post, id) post.Title = title post.Body = body
c.Txn.Save(&post)
c.Flash.Success(“포스트 수정 완료”) return c.Redirect(routes.Post.Show(id)) } // ➎ Create 메서드로 포스트 생성 func (c Post) Create(title, body string) revel.Result { post := models.Post{Title: title, Body: body} c.Txn.Create(&post) c.Flash.Success(“포스트 작성 완료”) return c.Redirect(routes.Post.Index()) } // ➏ Delete 메서드로 포스트 삭제 func (c Post) Destroy(id int) revel.Result { c.Txn.Where(“post_id = ?”, id).Delete(&models.Comment{}) c.Txn.Where(“id = ?”, id).Delete(&models.Post{}) c.Flash.Success(“포스트 삭제 완료”) return c.Redirect(routes.Post.Index()) } func (c Post) New() revel.Result { post := models.Post{} return c.Render(post) } func (c Post) Edit(id int) revel.Result { var post models.Post c.Txn.First(&post, id) return c.Render(post) }

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