zhangzengfei
2023-09-04 e8e536d1cb52d2126c8c7ce2ba1c7a76f7208678
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package models
 
import "errors"
 
//报警声音表
type Voice struct {
    Id        string       `gorm:"column:id;primary_key;type:varchar(100);unique;" json:"id"`
    Name       string        `gorm:"column:name" json:"name"`
    Path       string         `gorm:"column:path" json:"path"`
}
 
func (Voice) TableName() string {
    return "voice"
}
 
func (v *Voice) Insert() (bool,error) {
    var tmp Voice
    if tmp.Exist(v.Name) {
        //return false, errors.New("文件不允许重名")
    }
    result := db.Table(v.TableName()).Create(&v)
    if result.Error != nil {
        return false, result.Error
    }
    if result.RowsAffected > 0 {
        return true, nil
    }
    return false, errors.New("新增失败")
}
 
func (v *Voice) Update() (bool,error) {
    var tmp Voice
    if tmp.Exist(v.Name) && tmp.Id != v.Id {
        return false, errors.New("同名文件已存在")
    }
    result := db.Table(v.TableName()).Save(&v)
    if result.Error != nil {
        return false, result.Error
    }
    if result.RowsAffected > 0 {
        return true, nil
    }
    return false, errors.New("更新失败")
}
 
func (v *Voice) Exist(name string) bool {
    dbSelect := db.Table(v.TableName()).Where("name=?", name).First(&v)
    if dbSelect.Error != nil || dbSelect.RowsAffected ==0 {
        return false
    }
    return true
}
 
func (v *Voice) FindAll() (list []Voice, err error) {
    err = db.Table(v.TableName()).Find(&list).Order("id asc").Error
    if err != nil {
        return nil,err
    }
    return list,nil
}
 
func (v *Voice) DeleteById(id string) (bool, error) {
    result := db.Exec("delete from "+v.TableName()+" where id=?", id)
    if result.Error !=nil {
        return false, result.Error
    }
    if result.RowsAffected > 0 {
        return true, nil
    }
    return false, errors.New("删除失败")
}