Go GORM many2many问题

时间:2017-10-24 00:13:25

标签: postgresql go foreign-keys many-to-many go-gorm

我无法找到向模型添加关联的最佳方法。我有以下结构

type Beer struct {
        ID             uint       `json:"id"`
    Name           string     `json:"name" gorm:"not null;" sql:"unique"`
    Description    string     `json:"description" gorm:"not null;"`
    ImageURL       string     `json:"image_url"`
    AlcoholContent float64    `json:"alcohol_content, default:0"`
    Featured       bool       `json:"featured"`
    BrewStart      time.Time  `json:"brew_start"`
    BrewEnd        time.Time  `json:"brew_end"` 
    Brewers        []Brewer   `gorm:"many2many:beer_brewers" json:"brewers"`
}

type Brewer struct {
    ID        uint       `json:"id"`
    FirstName string     `json:"first_name"`
    LastName  string     `json:"last_name"`
    Title     string     `json:"title"`
    Featured  bool       `json:"featured"`
    Beers     []Beer    `gorm:"many2many:beer_brewers" json:"beers"`
}

以下是我用数据库播种

的数据示例
Beer{
    Name:           "some pale ale",
    Description:    "a description of some pale ale",
    ImageURL:       "http://via.placeholder.com/350x150",
    AlcoholContent: 4.5,
    Featured:       false,
    BrewStart:      utils.ParseTime("30-10-2017 13:00 (AEDT)"),
    BrewEnd:        utils.ParseTime("14-11-2017 13:00 (AEDT)"),
    Brewers: []Brewer{
        Brewer{FirstName: "john", LastName: "smith", Title: "bottle shaker", Featured: false},
        Brewer{FirstName: "joe", LastName: "bloggs", Title: "bottle maker", Featured: true},
    },
},
Beer{
    Name:           "some lager",
    Description:    "a description of some pale ale",
    ImageURL:       "http://via.placeholder.com/350x150",
    AlcoholContent: 4.5,
    Featured:       false,
    BrewStart:      utils.ParseTime("30-10-2017 13:00 (AEDT)"),
    BrewEnd:        utils.ParseTime("14-11-2017 13:00 (AEDT)"),
    Brewers: []Brewer{
        Brewer{FirstName: "john", LastName: "smith", Title: "bottle shaker", Featured: false},
        Brewer{FirstName: "joe", LastName: "bloggs", Title: "bottle maker", Featured: true},
    },
},

但是,上面在Brewer表中创建了重复的Brewers。我的问题是,引用已经存在但不在Brewer表中创建另一个Brewer项目的Brewer的最佳方法是什么?..还有什么是将新Brewer附加到Beer集合中的最佳方法?

谢谢, 贾斯汀

4 个答案:

答案 0 :(得分:2)

尝试先制作啤酒,再酿造啤酒,然后使用 .append 方法将酿酒商添加到啤酒中。

http://jinzhu.me/gorm/associations.html#association-mode

// Start Association Mode
var user User
db.Model(&user).Association("Languages")
// `user` is the source, it need to be a valid record (contains primary key)
// `Languages` is source's field name for a relationship.
// If those conditions not matched, will return an error, check it with:
// db.Model(&user).Association("Languages").Error


// Query - Find out all related associations
db.Model(&user).Association("Languages").Find(&languages)


// Append - Append new associations for many2many, has_many, will replace current association for has_one, belongs_to
db.Model(&user).Association("Languages").Append([]Language{languageZH, languageEN})
db.Model(&user).Association("Languages").Append(Language{Name: "DE"})

答案 1 :(得分:1)

这里的想法如下 1.您独立创建酿酒者 2.附加它们后,如图所示添加主键字段“ BrewerId” 3.这将在Brewers表中查找Brewer,并将其添加到Beer中。

import (
    "time"

    "github.com/jinzhu/gorm"

    // used by gorm
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

type Beer struct {
    BeerId         uint      `json:"id"`
    Name           string    `json:"name" gorm:"not null;" sql:"unique"`
    Description    string    `json:"description" gorm:"not null;"`
    ImageURL       string    `json:"image_url"`
    AlcoholContent float64   `json:"alcohol_content, default:0"`
    Featured       bool      `json:"featured"`
    BrewStart      time.Time `json:"brew_start"`
    BrewEnd        time.Time `json:"brew_end"`
    Brewers        []Brewer  `json:"brewers" gorm:"many2many:beer_brewers;association_foreignkey:brewer_id;foreignkey:beer_id"`
}

type Brewer struct {
    BrewerId  uint   `json:"id"`
    FirstName string `json:"first_name"`
    LastName  string `json:"last_name"`
    Title     string `json:"title"`
    Featured  bool   `json:"featured"`
}

func migrate() {
    // Connection is the connection string
    connection := "host=%v port=%v user=%v dbname=%v password=%v sslmode=%v connect_timeout=%v"
    db, _ := gorm.Open("postgres", connection)
    db.AutoMigrate(&Beer{}, &Brewer{})
    db.Model(&Beer{}).Related(&Brewer{}, "Brewers")

    db.Create(&Brewer{FirstName: "justin"})
    db.Create(&Beer{
        Name:           "some lager",
    Description:    "a description of some pale ale",
    ImageURL:       "http://via.placeholder.com/350x150",
    AlcoholContent: 4.5,
    Featured:       false,
    BrewStart:      utils.ParseTime("30-10-2017 13:00 (AEDT)"),
    BrewEnd:        utils.ParseTime("14-11-2017 13:00 (AEDT)"),
    }).Association("Brewers").Append(&Brewer{BrewerId: 123,})
}

答案 2 :(得分:0)

不确定您是否认为这是一个选项 - 更好的方法是在Beers.Brewers字段中保留对(一片)Brewer ID的引用。在对数据进行编码时,您可以将这些ID转换为完整的字段值(使用自定义的编组功能)。除非您考虑速度/性能,否则这可能是合适的。

答案 3 :(得分:0)

所以我想出了一个解决方案,我想在上面做什么。要将新的Brewer添加到Beer.Brewers集合中,我需要执行以下操作,

brewerr := Brewer{}
    db.Where(&Brewer{FirstName: "justin"}).Find(&brewerr)

beerr := Beer{}
    db.Preload("Brewers").Where(&Beer{Name: "some lager"}).Find(&beerr).Association("Brewers").Append(&brewerr)

值得注意的是,我需要首先Preload Beer.Brewers集合,然后添加。未能预加载会导致覆盖覆盖Brewers的所有Beer