gorm 如何让查询没找到数据时不报错

gorm 如何让查询没找到数据时不报错,第1张

func (m *ReplenishmentManager) searchReplRunWaveDefaultSettingRepo(ctx context.Context, whsId, operator string) (*ReplenishmentRunWaveDefaultSettingEntity, *wmserror.WMSError) {
	model := ReplenishmentRunWaveDefaultSettingEntity{}
	err := getReplenishmentRunWaveDefaultSettingSqlCommon(ctx).Where("whs_id = ? and  operator = ?", whsId, operator).Find(&model).GetError()
	if err != nil {
		return nil, wmserror.NewError(constant.ErrDB, err.Error())
	}
	return &model, nil
}

没找到数据时会报错

如果不想让其报错,可以把接收数据的结构体指针换成结构体指针数组,没有数据时不报错,数组长度为0

func (m *ReplenishmentManager) searchReplRunWaveDefaultSettingRepo(ctx context.Context, whsId, operator string) (*ReplenishmentRunWaveDefaultSettingEntity, *wmserror.WMSError) {
	var records []*ReplenishmentRunWaveDefaultSettingEntity
	err := getReplenishmentRunWaveDefaultSettingSqlCommon(ctx).Where("whs_id = ? and  operator = ?", whsId, operator).Find(&records).GetError()
	//换成数组后,没找到数据不会报record not found,这里的err是数据库出现问题,无法正常使用,err不能忽略
	if err != nil {
		return nil, wmserror.NewError(constant.ErrDB, err.Error())
	}
	if len(records) == 0 {
		return nil, nil
	}
	return records[0], nil
}


有问题可以评论一起探讨

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/994193.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存