gorm scan查询报了Scan error on column index 0, name \“count\“: converting NULL to int is unsupported

解决方案1:

使用sql.NullInt64。

只做简单记录。

示例:

func (o OrderModel) GetInfoByUid(ctx context.Context, id string, fields string) (sql.NullInt64, error) {
	var count sql.NullInt64
	db := o.db
	db = db.WithContext(ctx)
	err := db.Table(OrderTableName()).Select("sum(id)").Where("id = ?", id).Scan(&count).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return count, err
	}
	return count, nil
}

解决方案2:定义为指针也不会报错

示例:

func (o OrderModel) GetInfoByUid2(ctx context.Context, id string, fields string) (*int, error) {
	var count *int
	db := o.db
	db = db.WithContext(ctx)
	err := db.Table(OrderTableName()).Select("sum(id)").Where("id = ?", id).Scan(&count).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return count, err
	}
	return count, nil
}

直接定义为int就会报错:从错误来看,也很好理解。

报错示例:

func (o OrderModel) GetInfoByUid3(ctx context.Context, id string, fields string) (int, error) {
	var count int
	db := o.db
	db = db.WithContext(ctx)
	err := db.Table(OrderTableName()).Select("sum(id)").Where("id = ?", id).Scan(&count).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return count, err
	}
	return count, nil
}

你可能感兴趣的:(数据库)