News.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package System
  2. import (
  3. "fmt"
  4. "github.com/beego/beego/v2/adapter/orm"
  5. orm2 "github.com/beego/beego/v2/client/orm"
  6. "time"
  7. )
  8. type News struct {
  9. Id int `orm:"column(ID);size(11);auto;pk"`
  10. T_uuid string `orm:"size(256);null"` //
  11. T_Title string `orm:"size(256);null"` // 标题
  12. T_Url string `orm:"size(256);null"` // 地址
  13. T_Tag int `orm:"size(2);null"` // 标记 0未阅读 1 已阅读
  14. CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now 每次 model 保存时都会对时间自动更新
  15. }
  16. type News_R struct {
  17. Id int
  18. T_uuid string
  19. T_Title string
  20. T_Url string
  21. T_Tag int
  22. CreateTime string
  23. }
  24. func (t *News) TableName() string {
  25. return "news" // 数据库名称
  26. }
  27. func init() {
  28. //注册模型
  29. orm.RegisterModel(new(News))
  30. }
  31. func NewsToNews_R(r News) (m News_R) {
  32. m.Id = r.Id
  33. m.T_uuid = r.T_uuid
  34. m.T_Title = r.T_Title
  35. m.T_Url = r.T_Url
  36. m.T_Tag = r.T_Tag
  37. m.CreateTime = r.CreateTime.Format("2006-01-02 15:04:05")
  38. return
  39. }
  40. // 添加
  41. func Add_News(r News) (id int64, err error) {
  42. o := orm.NewOrm()
  43. r.T_Tag = 0
  44. id, err = o.Insert(&r)
  45. if err != nil {
  46. fmt.Println(err)
  47. }
  48. return id, err
  49. }
  50. // 获取列表
  51. func Read_News_List(T_uuid string, T_Title string, T_Tag int, page int, page_z int) (r_ []News_R, cnt int64) {
  52. o := orm.NewOrm()
  53. // 也可以直接使用 Model 结构体作为表名
  54. qs := o.QueryTable(new(News))
  55. var offset int64
  56. if page <= 1 {
  57. offset = 0
  58. } else {
  59. offset = int64((page - 1) * page_z)
  60. }
  61. // 过滤
  62. cond := orm.NewCondition()
  63. cond1 := cond.And("T_uuid", T_uuid) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
  64. if len(T_Title) > 0 {
  65. //cond1.AndCond(cond.And("T_class", class))
  66. cond1 = cond1.And("T_Title__icontains", T_Title)
  67. }
  68. if T_Tag == 0 {
  69. cond1 = cond1.And("T_Tag", 0)
  70. }
  71. var r []News
  72. // 查询
  73. qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-Id").All(&r)
  74. cnt, _ = qs.SetCond((*orm2.Condition)(cond1)).Count()
  75. for _, v := range r {
  76. r_ = append(r_, NewsToNews_R(v))
  77. }
  78. return r_, cnt
  79. }
  80. // 修改 排序
  81. func Update_News_Tag(Id int, T_uuid string) (err error) {
  82. o := orm.NewOrm()
  83. v := News{Id: Id}
  84. if err = o.Read(&v, "Id"); err == nil {
  85. var num int64
  86. if v.T_uuid != T_uuid {
  87. return
  88. }
  89. v.T_Tag = 1
  90. if num, err = o.Update(&v, "T_Tag"); err == nil {
  91. fmt.Println("Number of records updated in database:", num)
  92. }
  93. }
  94. return
  95. }