1
votes

We're trying to use Gorm with mysql 8 to much frustration.

I have the following tables (simplified for brevity here)

type StoragePool struct {
    gorm.Model
    PoolId  string   `json:"id" gorm:"column:poolid;size:40;unique;not null"`
    Volumes []Volume `json:"volumes" gorm:"foreignkey:StorageId;association_foreignkey:PoolId"`
}

type Volume struct {
    gorm.Model
    StorageId string `json:"storageid" gorm:"column:storageid;size:40"`
}

Data insertions seem to work fine. Both tables get populated and no constraints are violated.

A query that expects a single record seems to work fine:

poolRecord := &StoragePool{}
if err := tx.Where("poolid = ?", pool.PoolId).First(&StoragePool{}).Scan(poolRecord).Error; err != nil {        
    return err
}

This query only returns a single row. When I perform this exact query as raw SQL outside of go, it returns all 31 records I expect.

var poolVolumes []Volume
if err := tx.Where("storageid = ?", pool.PoolId).Find(&Volume{}).Scan(&poolVolumes).Error; err != nil {
    return err
}
log.Debugf("found %d volumes belonging to %q [%s]", len(poolVolumes), pool.Name, pool.PoolId)

According to the docs, that second sql statement is the equivalent of "SELECT * FROM VOLUMES WHERE STORAGEID = 'poolid'". That is not the behavior I am getting.

Anyone have any ideas what I'm doing wrong here?

1
sanity check the value : pool.PoolId is correctdiyoda_

1 Answers

8
votes

I rarely use an ORM while coding with go, but following the doc from gorm, it seems like you are doing it the wrong way.

Scan is used for scanning result into another struct, like this:

type Result struct {
  Name string
  Age  int
}

var result Result
db.Table("users").Select("name, age").Where("name = ?", 3).Scan(&result)

var poolVolumes []Volume
if err := tx.Where("storageid = ?", pool.PoolId).Find(&poolVolumes).Error; err != nil {
    return err
}