Your Question
Hi, I am getting an unsupported data type: <nil> while trying to retrieve associated data. I can see it in the database and it's probably me doing something incorrectly.
Can anyone help?
This is my command, if I remove the Association then everything seems to work so the "FirstOrCreate" is working.
block := model.Block{
Filename: "test.blk",
}
err := s.dbConnection.DB.FirstOrCreate(&block).Association("BlockVersion").Find(&block.BlockVersion)
if err != nil {
log.Fatalln("There was error :- ", err)
}
Here are my models.
type BlockVersion struct {
gorm.Model
BlockID uint
Filesize int64
}
type Block struct {
gorm.Model
Filename string
BlockVersion []BlockVersion
}
Once I have it working, the BlockVersion may contain more than 1 record, so I was hoping to return "only" the latest one.
I have placed some images below to show what is currently in the database.
Expected answer
I would like for the last (latest) record of "BlockVersion" to be populated inside the "Block".
Block
BlockVersion
Comment From: iangregsondev
Oh,
I got it working.
Seems I might have been doing it wrong.
I am now using
err = s.dbConnection.DB.Model(&block).Association("BlockVersion").Find(&block.BlockVersion)
This now works.
So doing this does not.
s.dbConnection.DB.FirstOrCreate(&block) // Get main table first
err := s.dbConnection.DB.FirstOrCreate(&block).Association("BlockVersion").Find(&block.BlockVersion)
I thought you could chain then?
Comment From: a631807682
After a Chain method, Finisher Method, GORM returns an initialized gorm.DB instance, which is NOT safe to reuse anymore, you should use a New Session Method to mark the gorm.DB as shareable.
https://gorm.io/docs/method_chaining.html#New-Session-Method