gorm first默认带主键排序解决方法

 判断字段是否有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
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值