fusenapi/model/gmodel/fs_user_material_logic.go

78 lines
2.1 KiB
Go
Raw Normal View History

2023-08-02 10:14:53 +00:00
package gmodel
2023-08-03 06:38:17 +00:00
import (
"context"
2023-08-03 09:37:25 +00:00
"fusenapi/utils/handlers"
2023-08-03 06:38:17 +00:00
"reflect"
"gorm.io/gorm"
)
2023-08-02 10:14:53 +00:00
// 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
}
2023-08-03 06:38:17 +00:00
func (m *FsUserMaterialModel) FindAll(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string, orderBy string) ([]*FsUserMaterial, error) {
var resp []*FsUserMaterial
// 过滤
if filterMap != nil {
2023-08-03 09:37:25 +00:00
rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap))
2023-08-03 06:38:17 +00:00
}
// 排序
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{}{}
}
2023-08-03 09:37:25 +00:00
rowBuilder = rowBuilder.Scopes(handlers.OrderCheck(orderBy, fieldsMap))
2023-08-03 06:38:17 +00:00
}
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
}
2023-08-07 09:19:55 +00:00
// 获取最新记录
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
}
2023-08-10 04:30:53 +00:00
func (m *FsUserMaterialModel) FindOneById(ctx context.Context, id int64) (resp *FsUserMaterial, err error) {
err = m.db.WithContext(ctx).Model(&FsUserMaterial{}).Where("id = ?", id).Take(&resp).Error
return resp, err
}