du5591 2015-10-01 00:46
浏览 60

无法通过Golang Orm库创建关联

I've been trying to use the Associations feature in golang orm (https://github.com/jinzhu/gorm/), and am unable to create a pretty simple association. In the example below, the user table contains data, but email table does not. I've tried a bunch of things and I'm probably missing something basic, but have been unable to find the right answer in github/stackoverflow.

Code :

package main

import (
    "database/sql"
    "log"

    "github.com/jinzhu/gorm"
    "github.com/mattn/go-sqlite3"
)

var db gorm.DB

type User struct {
    Name   string
    Mail   Email
}

type Email struct {
    Address string
}

//Initialize DB .
func InitDB() {
    var DB_DRIVER string
    sql.Register(DB_DRIVER, &sqlite3.SQLiteDriver{})
    log.Printf("Initializing Database with ", DB_DRIVER)
    dbSql, _ := sql.Open(DB_DRIVER, "simple-sqlite")

    var err error
    db, err = gorm.Open("sqlite3", dbSql)

    if err != nil {
        log.Fatalf("Got error when connecting to the database, the error is '%v'", err)
    }

    db.LogMode(true)
    // Then you could invoke `*sql.DB`'s functions with it
    db.DB().Ping()
    db.DB().SetMaxIdleConns(10)
    db.DB().SetMaxOpenConns(100)

    // Disable table name's pluralization
    db.SingularTable(true)
}

func InitSchema() {
    db.CreateTable(&User{}, &Email{})
}

func DoStuff() {
    user := User{Name: "Jinzhu", Mail: Email{Address: "hello@hello.com"}}
    db.Create(&user)
}

func main() {
    InitDB()
    InitSchema()
    DoStuff()
}

go run main.go prints the following output 2015/09/30 17:25:04 Initializing Database with %!(EXTRA string=)

[2015-09-30 17:25:04] [3.21ms] CREATE TABLE "user" ("name" varchar(255))

[2015-09-30 17:25:04] [4.01ms] CREATE TABLE "email" ("address" varchar(255) )

[2015-09-30 17:25:04] [0.54ms] INSERT INTO "user" ("name") VALUES ('Jinzhu')

Not sure what I'm missing here - appreciate any response!

  • 写回答

1条回答 默认 最新

  • drgmszo076956 2015-10-01 02:05
    关注

    You're missing your primary/foreign key references for each of your models, here's the updated code:

    package main
    
    import (
        "database/sql"
        "log"
    
        "github.com/jinzhu/gorm"
        "github.com/mattn/go-sqlite3"
    )
    
    var db gorm.DB
    
    type User struct {
        ID     uint `gorm:"primary_key"`
        Name   string
        Mail   Email
        MailID sql.NullInt64
    }
    
    type Email struct {
        ID      uint `gorm:"primary_key"`
        Address string
    }
    
    //Initialize DB .
    func InitDB() {
        var DB_DRIVER string
        sql.Register(DB_DRIVER, &sqlite3.SQLiteDriver{})
        log.Printf("Initializing Database with ", DB_DRIVER)
        dbSql, _ := sql.Open(DB_DRIVER, "simple-sqlite")
    
        var err error
        db, err = gorm.Open("sqlite3", dbSql)
    
        if err != nil {
            log.Fatalf("Got error when connecting to the database, the error is '%v'", err)
        }
    
        db.LogMode(true)
        // Then you could invoke `*sql.DB`'s functions with it
        db.DB().Ping()
        db.DB().SetMaxIdleConns(10)
        db.DB().SetMaxOpenConns(100)
    
        // Disable table name's pluralization
        db.SingularTable(true)
    }
    
    func InitSchema() {
        db.CreateTable(&User{}, &Email{})
    }
    
    func DoStuff() {
        user := User{Name: "Jinzhu", Mail: Email{Address: "hello@hello.com"}}
        db.Create(&user)
    }
    
    func main() {
        InitDB()
        InitSchema()
        DoStuff()
    }
    

    notice the primary keys on the User and Email structs as well as the foreign key reference on User

    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来