더북(TheBook)

포스트를 조회할 때 포스트에 속한 댓글도 함께 조회되도록 포스트 컨트롤러에서 포스트를 조회하는 부분인 getPost() 메서드를 수정하자.

▼ app/controllers/post.go

func getPost(txn *sql.Tx, id int) (models.Post, error) {
    post := models.Post{}
    err := txn.QueryRow(“select id, title, body, created_at, updated_at from posts where id=?”, id).
        Scan(&post.Id, &post.Title, &post.Body, &post.CreatedAt, &post.UpdatedAt)
 
switch { case err == sql.ErrNoRows: return post, fmt.Errorf(“No post with that ID - %d.”, id) case err != nil: return post, err }
// 포스트의 댓글 조회 post.Comments = getComments(txn, id)
return post, nil } func getComments(txn *sql.Tx, postId int) (comments []models.Comment) { rows, err := txn.Query(“select id, body, commenter, post_id, created_at, updated_at from comments where post_id=? order by created_at desc”, postId) if err != nil { panic(err) }
for rows.Next() { comment := models.Comment{} if err := rows.Scan(&comment.Id, &comment.Body, &comment.Commenter, &comment. PostId, &comment.CreatedAt, &comment.UpdatedAt); err != nil { panic(err) } comments = append(comments, comment) } return }

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