无法使GORM关联按预期工作

My two models are

package models

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

// Businesses ...
type Businesses []Business

and

package models

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

// Tables ...
type Tables []Table

It may be obvious from the code, but the association should be that one 'business' has many 'tables' and a 'table' belong to a 'business'. However, when the database is created there are no foreign keys created (I am using sqlite3) and when I return the business which has been created with

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

the businesses array is empty, and when the table is returned although the business_id is correct, there is business struct is empty also.

I could not reproduce your problem. I have a working solution here. I suspected that it would not work with the entities in a separate models package, but that worked as well.

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