You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.0 KiB
87 lines
2.0 KiB
package app
|
|
|
|
import (
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"math"
|
|
"strings"
|
|
)
|
|
|
|
// DB 用户数据操作
|
|
var DB *gorm.DB
|
|
|
|
func ConfigGormDB() {
|
|
var err error
|
|
DB, err = gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if err = DB.AutoMigrate(&User{}, &Goods{}, &Price{}); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
// User 用户
|
|
type User struct {
|
|
gorm.Model
|
|
Name string `json:"name"` // 用户名称
|
|
PhoneNumber string `json:"phone_number"` // 用户手机
|
|
Password string `json:"password"` // 登录密码
|
|
}
|
|
|
|
// Goods 商品
|
|
type Goods struct {
|
|
gorm.Model
|
|
Name string `json:"name"` // 商品名称
|
|
Price float32 `json:"price"` // 商品当前价格
|
|
Prices []Price `json:"prices,omitempty"` // 商品价格列表
|
|
}
|
|
|
|
// Price 商品价格
|
|
type Price struct {
|
|
gorm.Model
|
|
GoodsID uint `json:"goods_id"` // 管理商品
|
|
Price float32 `json:"price"` // 商品价格
|
|
}
|
|
|
|
// Paginate 分页查询作用域
|
|
func Paginate(r *Request) func(db *gorm.DB) *gorm.DB {
|
|
return func(db *gorm.DB) *gorm.DB {
|
|
page := r.Int("page", 1, func(p int) int {
|
|
return int(math.Max(float64(p), 1))
|
|
})
|
|
perPage := r.Int("per_page", 30, func(i int) int {
|
|
return int(math.Max(float64(i), 1))
|
|
})
|
|
offset := (page - 1) * perPage
|
|
return db.Offset(offset).Limit(perPage)
|
|
}
|
|
}
|
|
|
|
// Search 搜索作用域
|
|
func Search(r *Request, key, query string) func(db *gorm.DB) *gorm.DB {
|
|
return func(db *gorm.DB) *gorm.DB {
|
|
if keyword, ok := r.Get(key); ok {
|
|
return db.Where(query, "%"+keyword+"%")
|
|
} else {
|
|
return db
|
|
}
|
|
}
|
|
}
|
|
|
|
// TimeRange 时间范围作用域
|
|
func TimeRange(r *Request, column string) func(db *gorm.DB) *gorm.DB {
|
|
return func(db *gorm.DB) *gorm.DB {
|
|
var queries []string
|
|
var args []any
|
|
if val, ok := r.Get("start_time"); ok {
|
|
queries = append(queries, column+" >= ?")
|
|
args = append(args, val)
|
|
}
|
|
if val, ok := r.Get("end_time"); ok {
|
|
queries = append(queries, column+" <= ?")
|
|
args = append(args, val)
|
|
}
|
|
return db.Where(strings.Join(queries, " AND "), args...)
|
|
}
|
|
}
|
|
|