Tino
Tino

Reputation: 3368

Gorm and relationships

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

Upvotes: 1

Views: 4248

Answers (2)

Tino
Tino

Reputation: 3368

The solution that made it work Link

db.Model(& TickerDataModel{}).AddForeignKey("ticker_id", "tickers(id)", "RESTRICT", "RESTRICT")

Upvotes: 0

alrx
alrx

Reputation: 11

See the section http://jinzhu.me/gorm/associations.html#has-many

I assume TickerModel has many TickerDataModel. The following model setup should do the trick.

type TickerModel struct {
    gorm.Model
    Name        string
    Symbol      string
    TickerData  []tickerdata.TickerDataModel
}


type TickerDataModel struct {
    gorm.Model
    Rank           int
    TickerModelID  uint
}

Create a relation with (http://jinzhu.me/gorm/crud.html#associations)

tickerModel := TickerModel{
    Name:       "foo",
    Symbol:     "bar",
    TickerData: []TickerDataModel{
        {Rank: "1"},
        {Rank: "2"},
    },
}

db.Create(&tickerModel)

Load TickerModels and TickerDataModels in the TickerData slices with (http://jinzhu.me/gorm/crud.html#preloading-eager-loading)

db.Preload("TickerData").Find(&tickerModels)

Upvotes: 1

Related Questions