简体   繁体   中英

gorm for mysql: record not found

 // for trade_service
 type AmountConfig struct {
    MaxCny float64 `thrift:"max_cny,1" json:"max_cny"`
    MaxBtc float64 `thrift:"max_btc,2" json:"max_btc"`
  }
  //

type AmountConfig struct {
     gorm.Model
     trade_service.AmountConfig  //
}



func getAmountConfig() (amount_config *trade_service.AmountConfig, err error) {
    db, err := getORMDB()
    if err != nil {
      logger.Errorln(err)
      return
    }

    var amountConfig AmountConfig{}

    if err = db.First(&amountConfig).Error; err != nil {
        logger.Errorln("getAmountConfig amount record does not exist:", err)
        return
    }

    amount_config = trade_service.NewAmountConfig()
    amount_config.MaxCny = amountConfig.MaxCny
    amount_config.MaxBtc = amountConfig.MaxBtc

    logger.Infoln("get amountConfig ok", amount_config)

    return
}

mysql table described as follow:

CREATE TABLE `amount_config` ( 
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `max_cny` decimal(65,2) DEFAULT NULL,
 `max_btc` decimal(65,4) DEFAULT NULL,
 `created_at` datetime DEFAULT NULL,
 `deleted_at` datetime DEFAULT NULL, 
 `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`), 
  KEY `updated_at` (`updated_at`),  
  KEY `created_at` (`created_at`),
  KEY `deleted_at` (`deleted_at`) 
  ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

I had a record in talbe "amount_config", but error displayed "record not found" , after I run the code "db.First(&amountConfig)".
Is there something wrong with my code ?

It's hard to tell without actual data, but I would say it's most likely about precision and rounding. Your data type is double and will most likely be sent as sql type double to mysql. It will be converted to numeric for the comparison, but it's precision will be somewhere around 15-18 digits after comma and likely won't be exactly what you specified in the code (eg 0.1 will likely become something like 0.10000000000005).

See more detailed explanations here and here

You might be able to fix this by adding explicit gorm mapping for that fields as numeric (see gorm documentation for exact format). But I'd rather suggest using github.com/shopspring/decimal instead, so that you always know exact precision you're working with. Explicitly mapping those fields as numeric would be still a good idea.

This is a known intentional issue of the gorm ORM. It returns error, record not found , when returned list by err:= db.Preload("UserDevices").First(&user, userID.ID).Error is empty. for further detail you can have a look at this github issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM