fusenapi/model/gmodel/fs_user_material_logic.go
laodaming 2668c232b1 fix
2023-09-04 18:54:03 +08:00

90 lines
2.5 KiB
Go

package gmodel
import (
"context"
"fmt"
"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) {
var cond string
if userId != 0 {
cond = fmt.Sprintf("user_id = %d", userId)
} else {
cond = fmt.Sprintf("guest_id = %d", guestId)
}
db := m.db.WithContext(ctx).Model(&FsUserMaterial{}).
Where(cond).
Order("id DESC")
err = db.Take(&resp).Error
return resp, err
}
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
}
func (m *FsUserMaterialModel) GetListByUser(ctx context.Context, userId, guestId int64, limit int) (resp *FsUserMaterial, err error) {
var cond string
if userId != 0 {
cond = fmt.Sprintf("user_id = %d", userId)
} else {
cond = fmt.Sprintf("guest_id = %d", guestId)
}
err = m.db.WithContext(ctx).Model(&FsUserMaterial{}).
Where(cond).Order("id DESC").Limit(limit).Find(&resp).Error
return resp, err
}