【问题标题】:Can't get GORM associations to work as expected无法让 GORM 关联按预期工作
【发布时间】:2018-05-31 17:04:00
【问题描述】:

我的两个模型是

package models

// Business ...
type Business struct {
    ID     uint
    Name   string `gorm:"not null"`
    Tables Tables `gorm:"ForeignKey:BusinessID"`
}

// Businesses ...
type Businesses []Business

package models

// Table ...
type Table struct {
    ID         uint
    Ref        string `gorm:"not null"`
    Business   Business
    BusinessID uint
}

// Tables ...
type Tables []Table

从代码中可能很明显,但关联应该是一个'business'有许多'table',一个'table'属于一个'business'。但是,创建数据库时没有创建外键(我使用的是 sqlite3),当我返回已创建的业务时

 bus := models.Business{
        Name: "Test",
        Tables: models.Tables{
        models.Table{Ref: "A1"},
    },
}
db.Create(&bus)

businesss数组为空,返回表时business_id虽然正确,但也有business struct为空。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    我无法重现您的问题。我在这里有一个可行的解决方案。我怀疑它不适用于单独模型包中的实体,但效果也很好。

    package main
    
    import (
        "log"
    
        "github.com/jinzhu/gorm"
        _ "github.com/jinzhu/gorm/dialects/sqlite"
        _ "github.com/mattn/go-sqlite3"
    )
    
    type Business struct {
        ID     uint
        Name   string `gorm:"not null"`
        Tables Tables `gorm:"ForeignKey:BusinessID"`
    }
    
    type Table struct {
        ID         uint
        Ref        string `gorm:"not null"`
        Business   Business
        BusinessID uint
    }
    
    type Tables []Table
    type Businesses []Business
    
    func main() {
        var err error
        var db *gorm.DB
    
        db, err = gorm.Open("sqlite3", "test.db")
        if err != nil {
            log.Fatal(err)
        }
    
        defer db.Close()
    
        db.LogMode(true)
        db.AutoMigrate(&Business{})
        db.AutoMigrate(&Table{})
    
        bus := Business{
            Name: "Test",
            Tables: Tables{
                Table{Ref: "A1"},
            },
        }
        db.Create(&bus)
        var businesses Businesses
        db.Preload("Tables").Find(&businesses)
        log.Println(businesses)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      相关资源
      最近更新 更多