判断字段是否有orderBy,有的话用Take,没有就用First
// QueryOne 查询单条数据
func (r *DBRepository) QueryOne(condition string, args []interface{}, dest interface{}, options ...map[string]interface{}) error {
query := r.QueryBuilder(condition, args, options...)
var err error
//判断options是否有orderBy字段,如果有则不使用First方法,First方法会自动加上主键排序
if len(options) != 0 && len(options[0]) != 0 {
option := options[0]
if orderBy, ok := option["orderBy"].(string); ok && orderBy != "" {
err = query.Take(dest).Limit(1).Error
}
} else {
err = query.First(dest).Error
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return err
}
// QueryBuilder 构建查询条件
func (r *DBRepository) QueryBuilder(condition string, args []interface{}, options ...map[string]interface{}) *gorm.DB {
query := r.db().Where(condition, args...)
if len(options) != 0 && len(options[0]) != 0 {
option := options[0]
//指定字段
if selectField, ok := option["select"].(string); ok && selectField != "" {
query = query.Select(selectField)
}
var limit int
if pageSize, ok := option["page_size"].(int); ok && pageSize > 0 {
limit = pageSize
query = query.Limit(limit)
}
if page, ok := option["page"].(int); ok && page > 0 {
query = query.Offset((page - 1) * limit)
}
// 处理排序参数
if orderBy, ok := option["orderBy"].(string); ok && orderBy != "" {
query = query.Order(orderBy)
}
// 处理分组参数
if groupBy, ok := option["groupBy"].(string); ok && groupBy != "" {
query = query.Group(groupBy)
}
}
if r.isNew && r.locked == 1 {
query.Clauses(clause.Locking{Strength: "UPDATE"})
}
if r.isNew && r.locked == 2 {
query.Clauses(clause.Locking{
Strength: "SHARE",
Table: clause.Table{Name: clause.CurrentTable},
})
}
return query
}
使用
var tblWithholdSignStruct user_info_model.TblWithholdSignModel
// 查询签约号
condition := "alipay_user_id = ? AND status = ? AND is_zft = ?"
options := map[string]interface{}{
"select": "id,agreement_no", // 指定要查询的字段
"orderBy": "id DESC",
}
args := []interface{}{aliPayUserId, 10, f.isZft}
err = f.svc.Repo.TblWithholdSignRepository.QueryOne(condition, args, &tblWithholdSignStruct, options)
if err != nil {
return nil, err
}