fusenapi/model/gmodel/fs_user_material_logic.go
laodaming 74708d3b21 fix
2023-08-07 17:19:55 +08:00

73 lines
1.9 KiB
Go

package gmodel
import (
"context"
"fusenapi/utils/handlers"
"reflect"
"gorm.io/gorm"
)
// TODO: 使用model的属性做你想做的
func (p *FsUserMaterialModel) CreateOrUpdate(ctx context.Context, req *FsUserMaterial) (resp *FsUserMaterial, err error) {
rowBuilder := p.db.Table(p.name).WithContext(ctx)
if req.Id > 0 {
err = rowBuilder.Save(req).Error
} else {
err = rowBuilder.Create(req).Error
}
return req, err
}
func (m *FsUserMaterialModel) FindAll(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string, orderBy string) ([]*FsUserMaterial, error) {
var resp []*FsUserMaterial
// 过滤
if filterMap != nil {
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
}
// 排序
if orderBy != "" {
var fieldsMap = make(map[string]struct{})
s := reflect.TypeOf(&FsUserMaterial{}).Elem() //通过反射获取type定义
for i := 0; i < s.NumField(); i++ {
fieldsMap[s.Field(i).Tag.Get("json")] = struct{}{}
}
rowBuilder = rowBuilder.Scopes(handlers.OrderCheck(orderBy, fieldsMap))
}
result := rowBuilder.WithContext(ctx).Find(&resp)
if result.Error != nil {
return nil, result.Error
} else {
return resp, nil
}
}
func (m *FsUserMaterialModel) RowSelectBuilder(selectData []string) *gorm.DB {
var rowBuilder = m.db.Table(m.name)
if selectData != nil {
rowBuilder = rowBuilder.Select(selectData)
} else {
rowBuilder = rowBuilder.Select("*")
}
return rowBuilder
}
// 获取最新记录
func (m *FsUserMaterialModel) FindLatestOne(ctx context.Context, userId int64, guestId int64) (resp FsUserMaterial, err error) {
if userId == 0 && guestId == 0 {
return FsUserMaterial{}, nil
}
db := m.db.WithContext(ctx).Model(&FsUserMaterial{}).Order("id DESC")
if userId != 0 {
db = db.Where("`user_id` = ?", userId)
} else {
db = db.Where("`guest_id` = ?", guestId)
}
err = db.Take(&resp).Error
return resp, err
}