douxi7219 2017-11-28 19:29
浏览 23
已采纳

政府和关系

I'm new to Golang and even more to Gorm. I'm trying to get a one-to-many relationship going. Basically there is one ticker symbol and his many ticker data. Everything works well, except that I cannot get the relationship on the models going. I just need a little hint on how to do that (best practise welcome).

main.go

package main

import (
    "github.com/jinzhu/gorm"
    "github.com/khwerhahn/quoteworker/common"
    "github.com/khwerhahn/quoteworker/tickerdata"
    "github.com/khwerhahn/quoteworker/ticker"
)

// Migrate database
func Migrate(db *gorm.DB) {
    ticker.AutoMigrate()
    tickerdata.AutoMigrate()
}

func main() {
    db := common.Init()
    Migrate(db)
    defer db.Close()
    //// more code....
}

Lives in it own file and package. model.gofor ticker

package ticker

import (
    "github.com/jinzhu/gorm"
    "github.com/khwerhahn/quoteworker/common"
)

type TickerModel struct {
    gorm.Model
    Name   string `gorm:"column:name;unique_index"`
    Symbol string `gorm:"column:symbol;unique_index"`
}

// AutoMigrate the schema of database if needed
func AutoMigrate() {
    db := common.GetDB()
    db.AutoMigrate(&TickerModel{})
}

Lives in it own file and package. model.go for tickerdata

package tickerdata

import (
    "github.com/jinzhu/gorm"
    "github.com/khwerhahn/quoteworker/common"
    "github.com/khwerhahn/quoteworker/ticker"
)

type TickerDataModel struct {
    gorm.Model
    Rank                           int     `gorm:"column:rank"`
    // left out some stuff....
    TickerModel                     ticker.TickerModel
    TickerModelID                   uint `gorm:"column:tickerId"`
}

// AutoMigrate the schema of database if needed
func AutoMigrate() {
    db := common.GetDB()
    db.AutoMigrate(&TickerDataModel{})
}

Thx

  • 写回答

2条回答 默认 最新

  • doujiang6944 2017-12-02 08:17
    关注

    The solution that made it work Link

    db.Model(& TickerDataModel{}).AddForeignKey("ticker_id", "tickers(id)", "RESTRICT", "RESTRICT")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程