Golang的GORM没有为“有很多”的关系添加关联

I just started using GORM and tried to build a "has many relationship". I'm trying to add an association to Previous.Holdings (I think I followed the docs correctly) but when I try to do a select * from previous I don't see anything showing up in the database. Any idea on what I'm missing.

import (
    orm "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)    

type Previous struct {
    orm.Model

    Holdings []Holding `gorm:"foreignkey:ID"`
}

type Holding struct {
    ID uint `gorm:"primary_key"`

    Symbol string
    PurchaseDate time.Time
    SellDate time.Time
}

func main() {
    t1, _ := time.Parse("2006-01-02", "2017-06-16")
    h := Holding{
        Symbol: "abc",
        PurchaseDate: t1,
    }
    db.Model(&Previous{}).Association("Holdings").Append(h)
}

First of all you should create your previous table. You can make that by making migrations. You probably should make that migrations after db connection initialization. e.g.

db.AutoMigrate(&Previous{})

So when u using db.Model(&Previous{}) you not saving any entity and if u wanna make asscociation with Holdings entity you need as first step to Save or Find existing Previous record by doing e.g.

previous := &Previous{}
db.Save(previous)

After that you can append your holding record to Model like you do in your code but changing referenced Previous. So it will look like this

h := Holding{
    Symbol:       "abc",
    PurchaseDate: t1,
}
db.Model(previous).Association("Holdings").Append(h)

I don't know if its for testing but when you modeling entities you can make referenced id whithout specifing foreign key also you are using your Holding ID as ForeignKey so ID of Previous will be your ID of Holding.

For me your model declaration should look like this (PreviousID will be automaticaly signed as foreign key for Previous)

type Previous struct {
    orm.Model

    Holdings []Holding
}

type Holding struct {
    ID           uint `gorm:"primary_key"`
    PreviousID   uint
    Symbol       string
    PurchaseDate time.Time
    SellDate     time.Time
}