comment.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package dao
  2. import (
  3. "fmt"
  4. "github.com/RaymondCode/simple-demo/entities"
  5. "github.com/RaymondCode/simple-demo/util/snowflake"
  6. "gorm.io/gorm"
  7. "strconv"
  8. )
  9. func InsertAndGetComment(userId, content, videoId string) entities.Comment {
  10. fmt.Println(userId + " " + content + " " + videoId)
  11. uid, _ := strconv.ParseInt(userId, 10, 64)
  12. vid, _ := strconv.ParseInt(videoId, 10, 64)
  13. idval := snowflake.MakeInt64SnowFlakeId()
  14. node := entities.Comment{
  15. ID: idval,
  16. UserID: uid,
  17. VideoID: vid,
  18. Content: content,
  19. }
  20. Db.Transaction(func(tx *gorm.DB) error {
  21. // 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')
  22. if err := tx.Table("comment").Create(&node).Error; err != nil {
  23. // 返回任何错误都会回滚事务
  24. fmt.Println("create new comment error")
  25. return nil
  26. }
  27. if err := tx.Table("comment").Where("id = ?", idval).Limit(1).Find(&node).Error; err != nil {
  28. // 返回任何错误都会回滚事务
  29. fmt.Println("create new comment error")
  30. return nil
  31. }
  32. // 返回 nil 提交事务
  33. return nil
  34. })
  35. fmt.Printf("%+v\n", node)
  36. return node
  37. }
  38. func GetVideoCommentList(videoId string) []entities.Comment {
  39. var lists []entities.Comment
  40. Db.Table("comment").Where("video_id = ?", videoId).Debug().Find(&lists)
  41. return lists
  42. }