attachment.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //数据库模型.
  2. package models
  3. import (
  4. "time"
  5. "github.com/astaxie/beego/orm"
  6. "github.com/lifei6671/godoc/conf"
  7. "os"
  8. "github.com/astaxie/beego"
  9. )
  10. // Attachment struct .
  11. type Attachment struct {
  12. AttachmentId int `orm:"column(attachment_id);pk;auto;unique" json:"attachment_id"`
  13. BookId int `orm:"column(book_id);type(int)" json:"book_id"`
  14. DocumentId int `orm:"column(document_id);type(int);null" json:"doc_id"`
  15. FileName string `orm:"column(file_name);size(255)" json:"file_name"`
  16. FilePath string `orm:"column(file_path);size(2000)" json:"file_path"`
  17. FileSize float64 `orm:"column(file_size);type(float)" json:"file_size"`
  18. HttpPath string `orm:"column(http_path);size(2000)" json:"http_path"`
  19. FileExt string `orm:"column(file_ext);size(50)" json:"file_ext"`
  20. CreateTime time.Time `orm:"type(datetime);column(create_time);auto_now_add" json:"create_time"`
  21. CreateAt int `orm:"column(create_at);type(int)" json:"create_at"`
  22. }
  23. // TableName 获取对应数据库表名.
  24. func (m *Attachment) TableName() string {
  25. return "attachment"
  26. }
  27. // TableEngine 获取数据使用的引擎.
  28. func (m *Attachment) TableEngine() string {
  29. return "INNODB"
  30. }
  31. func (m *Attachment) TableNameWithPrefix() string {
  32. return conf.GetDatabasePrefix() + m.TableName()
  33. }
  34. func NewAttachment() *Attachment {
  35. return &Attachment{}
  36. }
  37. func (m *Attachment) Insert() error {
  38. o := orm.NewOrm()
  39. _, err := o.Insert(m)
  40. return err
  41. }
  42. func (m *Attachment) Update() error {
  43. o := orm.NewOrm()
  44. _, err := o.Update(m)
  45. return err
  46. }
  47. func (m *Attachment) Delete() error {
  48. o := orm.NewOrm()
  49. _,err := o.Delete(m)
  50. if err == nil {
  51. if err1 := os.Remove(m.FilePath); err1 != nil {
  52. beego.Error(err1)
  53. }
  54. }
  55. return err
  56. }
  57. func (m *Attachment) Find(id int) (*Attachment, error) {
  58. if id <= 0 {
  59. return m, ErrInvalidParameter
  60. }
  61. o := orm.NewOrm()
  62. err := o.QueryTable(m.TableNameWithPrefix()).Filter("attachment_id", id).One(m)
  63. return m, err
  64. }
  65. func (m *Attachment) FindListByDocumentId(doc_id int) (attaches []*Attachment, err error) {
  66. o := orm.NewOrm()
  67. _,err = o.QueryTable(m.TableNameWithPrefix()).Filter("document_id",doc_id).OrderBy("-attachment_id").All(&attaches)
  68. return
  69. }