duanjiyun7391 2018-03-26 02:38
浏览 99

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)
}
  • 写回答

1条回答 默认 最新

  • douli8428 2018-03-26 10:34
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分