简体   繁体   English

使用 GORM for Golang 的一对一关系映射

[英]One to One relation mapping using GORM for Golang

I am trying to understand how GORM works for one to one relational mapping with MySQL.我试图了解 GORM 如何与 MySQL 进行一对一的关系映射。 I have 2 structs like so:我有 2 个像这样的结构:

type User struct {
    Id              uint   `gorm:"AUTO_INCREMENT"`
    FirstName       string `gorm:"column:first_name"`
    LastName        string `gorm:"column:last_name"`
    EncryptedUserId string `gorm:"size:255"`
    Email           string `gorm:"not null;unique"`
    Password        string `gorm:"not null;unique"`
    CreatedAt       int64  `gorm:"type(timestamp)"`
}

type UserSession struct {
    Id           uint `gorm:"AUTO_INCREMENT"`
    UserId       User 
    SessionToken string `gorm:"column:session_token"`
    CreatedAt    int64  `gorm:"type(timestamp)"`
}

User and UserSession share one to one relation. UserUserSession共享一对一的关系。 But when code above is run, the column UserId for UserSession table is not created.但是当上面的代码运行时,不会创建UserSession表的UserId列。 Even after specifying the foreign key constraint gorm:"ForeignKey:Id" the result is same.即使在指定外键约束gorm:"ForeignKey:Id" ,结果也是一样的。 Why isn't the above code working?为什么上面的代码不起作用? Is anything missing in the struct definition?结构定义中是否缺少任何内容?

I can't comment your questions so I would ask it here: Do you migrate your schema in any way like:我无法评论您的问题,所以我会在这里问:您是否以任何方式迁移您的架构,例如:

db.AutoMigrate(&User{}, &UserSession{})

? ? If you do, you should get some detailed errors in log, which might be useful for you.如果你这样做,你应该在日志中得到一些详细的错误,这可能对你有用。

The way I have managed to get something similar to work is this.我设法获得类似于工作的方式是这样的。

type UserSession struct {
    Id           uint `gorm:"AUTO_INCREMENT"`
    UserId       uint
    User         User
    SessionToken string `gorm:"column:session_token"`
    CreatedAt    int64  `gorm:"type(timestamp)"`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM