2017-05-29 58 views
0

我的兩個型號無法讓GORM關聯按預期工作?

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 

這可能是顯而易見的代碼,但該協會應該是一個「業務」有許多「表」和「表」屬於到'商業'。但是,創建數據庫時有創建(我使用的sqlite3的),並沒有外鍵,當我返回已與

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

商家數組是空的,當表返回雖然創建的業務business_id正確,業務結構也是空的。

任何想法都會很棒!謝謝。

回答

0

我無法重現您的問題。我在這裏有一個工作解決方案。我懷疑它不會與單獨的模型包中的實體一起工作,但那也起作用。

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) 
}