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 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题