article_list.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package mint
  2. import (
  3. "net/http"
  4. "strconv"
  5. "github.com/gin-gonic/gin"
  6. "github.com/go-pg/pg/v10"
  7. "time"
  8. "encoding/json"
  9. )
  10. type ArticleList struct {
  11. Id int `form:"id" json:"id"`
  12. CollectionId int `form:"collection_id" json:"collection_id" binding:"required"`
  13. ArticleId int `form:"article_id" json:"article_id" binding:"required"`
  14. CreatedAt time.Time
  15. }
  16. type ArticleListHolder struct{
  17. Items []ArticleList
  18. }
  19. func (i *ArticleListHolder) UnmarshalJSON(b []byte) error{
  20. return json.Unmarshal(b, &i.Items)
  21. }
  22. //查询
  23. func GetCollectionArticleList(db *pg.DB) gin.HandlerFunc {
  24. return func(c *gin.Context) {
  25. cid,err:= strconv.Atoi(c.Param("cid"))
  26. if err != nil {
  27. panic(err)
  28. }
  29. // TODO 在这里进行db操作
  30. // Select user by primary key.
  31. var articles []ArticleList
  32. err = db.Model(&articles).Column("collection_id","article_id").Where("collection_id = ?",cid).Select()
  33. if err != nil {
  34. panic(err)
  35. }
  36. c.JSON(http.StatusOK, gin.H{
  37. "message": articles,
  38. })
  39. }
  40. }
  41. //修改
  42. func PostArticleListByArticle(db *pg.DB) gin.HandlerFunc{
  43. return func(c *gin.Context){
  44. aid,err:= strconv.Atoi(c.Param("aid"))
  45. if err != nil {
  46. panic(err)
  47. }
  48. //先删除
  49. _, err = db.Model((*ArticleList)(nil)).Where("article_id = ?",aid).Delete()
  50. if err != nil {
  51. panic(err)
  52. }
  53. var form ArticleListHolder
  54. if err := c.ShouldBindJSON(&form); err != nil {
  55. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  56. return
  57. }
  58. tx, err := db.Begin()
  59. if err != nil {
  60. panic(err)
  61. }
  62. defer tx.Rollback()
  63. stmt, err := tx.Prepare("INSERT INTO article_lists( collection_id, article_id ) VALUES( $1, $2 )")
  64. if err != nil {
  65. panic(err)
  66. }
  67. defer stmt.Close()
  68. for _, value := range form.Items{
  69. _, err = stmt.Exec(value.CollectionId,aid)
  70. if err != nil {
  71. panic(err)
  72. }
  73. }
  74. err = tx.Commit()
  75. if err != nil {
  76. panic(err)
  77. }
  78. c.JSON(http.StatusOK,gin.H{
  79. "message":"update ok",
  80. })
  81. }
  82. }