我一直在尝试使用golang orm(https://github.com/jinzhu/gorm/)中的关联功能,但无法创建非常简单的关联。 在下面的示例中,用户表包含数据,但电子邮件表不包含数据。 我尝试了很多东西,我可能遗漏了一些基本的东西,但一直无法在github / stackoverflow中找到正确的答案。
代码:
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打印以下输出 2015/09/30 17:25:04用%!初始化数据库(EXTRA string =)
[2015-09-30 17:25:04] [3.21ms]创建表"用户" ("名称" varchar(255))
[2015-09-30 17:25:04] [4.01ms]创建表"电子邮件" ("地址" varchar(255))
[2015-09-30 17:25:04] [0.54ms] INSERT INTO" user" ("名称")价值观(' Jinzhu')
不确定我在这里失踪了什么 - 感谢任何回应!
答案 0 :(得分:0)
您错过了每个模型的主要/外键引用,这里是更新后的代码:
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()
}
注意User
和Email
结构上的主键以及User
上的外键引用