package unity import ( "errors" "lot_interlligentControl/global" ) type PageParams struct { Page int `json:"page" form:"page"` Size int `json:"size" form:"size"` Desc string `json:"desc" form:"desc"` } // Paginate 使用给定的DB连接执行分页查询 func Paginate[T any](params PageParams, model T) (result []T, total int64, err error) { var count int64 if err = global.DBLink.Model(model).Count(&count).Error; err != nil { return nil, 0, err } // 计算偏移量并设置分页大小 offset := (params.Page - 1) * params.Size // 执行实际分页查询 if err = global.DBLink.Offset(offset).Limit(params.Size).Order(params.Desc).Find(&result).Error; err != nil { return nil, 0, err } return result, count, nil } // PaginateByID 根据ID进行分页查询 func PaginateByID[T any](id int, params PageParams, model T) (result []T, total int64, err error) { var count int64 if err = global.DBLink.Model(model).Where("create_by = ?", id).Count(&count).Error; err != nil { return nil, 0, err } // 计算偏移量并设置分页大小 offset := (params.Page - 1) * params.Size // 执行实际分页查询 if err = global.DBLink.Where("create_by = ?", id).Offset(offset).Limit(params.Size).Order(params.Desc).Find(&result).Error; err != nil { return nil, 0, err } return result, count, nil } // GetById 根据id查询 func GetById[T any](id int, model T) (T, error) { tx := global.DBLink.Where("id = ?", id).First(&model) if tx.Error != nil { return model, errors.New("查询失败") } else { return model, nil } } // DeleteById 根据id删除 func DeleteById[T any](id int, model T) (T, error) { tx := global.DBLink.Where("id = ?", id).Delete(&model) if tx.Error != nil { return model, errors.New("查询失败") } else { return model, nil } }