首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Go GORM many2many问题

Go GORM many2many问题
EN

Stack Overflow用户
提问于 2017-10-24 08:13:25
回答 4查看 4K关注 0票数 2

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

代码语言:javascript
复制
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"`
}

下面是我为数据库设定种子的数据示例

代码语言:javascript
复制
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。我的问题是,引用已经存在的酿酒商而不是在酿酒商table?..and中创建另一个酿酒商项的最佳方式是什么?

谢谢,贾斯汀

EN

回答 4

Stack Overflow用户

发布于 2017-10-24 11:30:21

尝试先创建啤酒,然后创建啤酒,并使用.append方法将啤酒添加到啤酒中。

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

代码语言:javascript
复制
// 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"})
票数 2
EN

Stack Overflow用户

发布于 2019-08-06 09:57:05

这里的想法如下1.您独立地创建啤酒2.当您追加它们时,添加主键字段"BrewerId“,如图3.这将在brewers表中查找Brewer并将其添加到啤酒中。

代码语言:javascript
复制
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,})
}
票数 1
EN

Stack Overflow用户

发布于 2017-10-24 14:57:45

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46900296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档