Gorm query returns only a single row, should return more


(Crashkid) #1

We’re trying to use Gorm with mysql 8 to much frustration. I apologize if this is the wrong forum for Gorm but haven’t had much luck getting help elsewhere.

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
}

The following 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?

Much thanks.


(Ali Koyuncu) #2

if err := tx.Where("storageid = ?", pool.PoolId).Find(&Volume{}).Scan(&poolVolumes).Error;

you don’t need to call scan and change &Volume to &poolVolumes

tx.Where("storageid = ?", pool.PoolId).Find(&poolVolumes)