type Users struct {
Id int `orm:"pk;auto"`
Username string
Password string
Salt string
Email string `orm:"unique"`
}
type Post struct {
Id int `orm:"pk;auto"`
Users *Users `orm:"rel(fk)"`
Author string
Title string `form:"title,text,Title:" valid:"MinSize(5); MaxSize(20)"`
Description string `form:textarea`
Date time.Time `orm:"auto_now_add;type(datetime)"`
}
我正在尝试为 Users
赋值,因为它是外键。我想分配登录的用户 ID。如何将 Users
结构中的用户 ID 分配给作为外键的 Post
结构中的用户 ID。
o := orm.NewOrm()
o.Using("default")
post := models.Post{}
users := models.Users{}
if this.Ctx.Input.Method() == "POST" {
inputs := this.Input()
post.Author = sess.(string)
post.Title = inputs.Get("title")
post.Description = inputs.Get("description")
post.Date = time.Now()
}
最佳答案
首先,回答你的问题:
post.Date = time.Now()
// This is your last line
// Up until now all good
post.Users = &users // Actually the naming is bad, should be post.User = user
o.Insert(users) // First create user
o.Insert(post) // Then insert post
这与 BeeGo ORM 提供的基本示例非常相似:https://beego.me/docs/mvc/model/orm.md
在现实世界中,您会注意到大多数时候您有一个用户,而您只想创建它一次。因此,您首先要将 Insert
切换为 ReadOrCreate
:https://beego.me/docs/mvc/model/object.md#readorcreate
话虽如此,根据我的经验,在 Go 中使用 MVC 和 ORM 框架并不是一个好主意。
关于go - 如何将用户 ID 分配给外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728565/