LoginSignup
0
3

More than 1 year has passed since last update.

Goでいいね機能を実装してみた。

Last updated at Posted at 2021-12-06

この記事は Aizu Advent Calendar 2021 の5日目の記事です

夏休み中にgo言語でそんな感じのコードを書いていたので、自分の復習も込めて記事にしてみます。
全てのコードはこちら

=> https://github.com/wt128/dbapiBygo/

フレームワーク等

gin/gorm/mysql

ER図とモデルergo.png

  • いいねのモデル
type Like struct{
    ID      uint `json:"id"`
    PostID  uint `json:"postid" gorm:"index:idx_name,unique"`
    UserID  uint `json:"userid" gorm:"index:idx_name,unique"`
    User    User `gorm:"foreignKey:UserID; references:ID; constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
    Post    Post `gorm:"foreignKey:PostID; references:ID; constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}

likeテーブルのpost_idとuser_idにはペアでユニーク制約をかけています。

  • いいね数のためのモデル
type CntList struct {
    Pid     uint    `json:"pid" gorm:"postid;"`
    Cnt     int64   `json:"cnt" gorm:"cnt;"`
}

gormで取得した後、jsonとして返すために構造体が必要なため用意しました。

コードと仕様

  • /like いいねの表示
  • /like/:id 特定のユーザー(id)のいいね数
  • /create 記事へのいいね
  • /destroy いいね取り消し
/like
    var cnt []CntList   
    db := db.GetDB()
    sql := db.Model(&Like{}).Select("COUNT(id) as cnt","post_id as pid").Group("pid").Find(&cnt)
/like/id
var cnt []CntList
    id := c.Params.ByName("id")
    db := db.GetDB()
    sql := db.Model(&Like{}).Where("user_id = ? ", id).Select("COUNT(id) as cnt","post_id as pid").Group("pid").Find(&cnt)
/create
    var com Like
    db := db.GetDB()
    //currrent_user
    if err := c.BindJSON(&com); err != nil{
        c.JSON(400,gin.H{"errorMessages":"エラーが発生しました."})
        return
    }
/destroy
db := db.GetDB()

    if err := c.BindJSON(&com); err != nil{
        c.JSON(400,gin.H{"errorMessages":"エラーが発生しました."})
        return
    }
    err := db.Where("post_id = ? and user_id= ?",com.PostID,com.UserID).Delete(&com)

参考

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3