这是我的代码:
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Mongo struct {
gorm.Model
Url string
Login string
Password string
Env string
Base string
Port string
}
type MicroService struct {
gorm.Model
Url string
Port string
Version string
Name string
Etat string
MongoDb Mongo `gorm:"foreignkey:MongoId"`
MongoId int
Env string
}
func initDb() {
var mongoDb Mongo
result := db.Find(&mongoDb, "env = ?", "Prod").RecordNotFound()
fmt.Println("not found create mongodb")
fmt.Println(result)
if result == true {
mongoDb = Mongo{}
// "mongodb://heroku_4n1snp42:f42hkq6n3qfv48uelms7vrclta@:23930/heroku_4n1snp42"
mongoDb.Url = "mlab.com"
mongoDb.Login = "toto"
mongoDb.Password = "titi"
mongoDb.Base = "tata"
mongoDb.Port = "23930"
mongoDb.Env = "Prod"
db.Create(&mongoDb)
}
var microService MicroService
result = db.Find(µService, "name = ? and env = ?", "constructProduct","Prod").RecordNotFound()
fmt.Println("not found create construct Product Micro")
fmt.Println(result)
if result == true {
microService = MicroService{}
microService.Name = "totobis"
microService.Port = "8307"
microService.Env = "Prod"
var mongoDbConstructProduct Mongo
result = db.Find(&mongoDbConstructProduct , "env = ?", "Prod").RecordNotFound()
fmt.Println(mongoDbConstructProduct)
microService.MongoDb = mongoDbConstructProduct
db.Create(µService)
fmt.Println("constructProduct microservice created")
}
}
var db *gorm.DB
var loggued bool
func main() {
var err error
loggued = false
db, err = gorm.Open("sqlite3", "configuration.sqlite3?cache=shared&mode=rwc")
db.AutoMigrate(&MicroService{})
db.AutoMigrate(&Mongo{})
initDb()
var microService MicroService
db.Find(µService, "name = ?", "totobis").RecordNotFound()
if err != nil {
panic("failed to connect database")
}
defer db.Close()
fmt.Println(microService)
}
但是我不明白为什么在查询对象后打印对象时,MicroService的mongodb为空。
当我在创建中打印字段mongodb时,就可以了:
{{1 2018-11-26 22:08:16.436503737 +0100 +0100 2018-11-26
22:08:16.504275897 +0100 +0100} mlab.com toto titi Prod tata
23930}
但是当我尝试重新创建微服务对象时,mongo字段为空:
{{2 2018-11-26 22:09:15.73203579 +0100 +0100 2018-11-26
22:09:15.73203579 +0100 +0100} 8307托托比斯{{0 0001-01-01
00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC}} 1产品}
如何通过关联的mongo结构获得良好的微服务结构?
最佳答案
MongoId是 uint数据类型,而不是int 。
您可以使用另一种方式在Mongo模型中将int字段用作:
type Mongo struct {
gorm.Model
Ms int // for example
....
}
然后在MicroService模型中:
type MicroService struct {
gorm.Model
Url string
Port string
Version string
Name string
Etat string
MongoDb Mongo `gorm:"foreignkey:MongoId;association_foreignkey:Ms"`
MongoId int
Env string
}
关于go - gorm中的外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53489209/