go - 如何将用户 ID 分配给外键

标签 go beego

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/

相关文章:

go - 在 golang 中,如果其中一个方法必须具有指针接收器,是否有必要将一种类型的所有方法更改为具有指针接收器?

html - Go Lang - 在目录结构中的什么地方放置用于 HTML 模板的图像?

几分钟后,Go 爬虫在从输出 channel 中选择时停止

go - 构建 Go 应用程序

web-applications - 跨多个包的全局 session 管理的命名空间/范围问题

mysql - 如何避免 "too many connections"

go - 如何通过Web程序集访问Go中的JS对象

api - beego 更新 & 通过 ID 获取 1

go - Beego如何支持HTTPS

go - Beego 跳过一些迁移