无法通过golang orm库创建关联

huangapple go评论82阅读模式
英文:

Unable to create Associations via golang orm library

问题

我一直在尝试使用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
}

//初始化数据库
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)
	//然后你可以使用`*sql.DB`的函数
	db.DB().Ping()
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	//禁用表名的复数形式
	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 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')

不确定我漏掉了什么 - 感谢任何回复!

英文:

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

得分: 1

你的模型中缺少主键和外键引用,以下是更新后的代码:

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
}

// 初始化数据库
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)
	// 可以使用 `*sql.DB` 的函数
	db.DB().Ping()
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	// 禁用表名的复数形式
	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` 上的外键引用

<details>
<summary>英文:</summary>

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

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


</details>



huangapple
  • 本文由 发表于 2015年10月1日 08:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/32877813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定