简体   繁体   中英

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. I have 2 structs like so:

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. But when code above is run, the column UserId for UserSession table is not created. Even after specifying the foreign key constraint gorm:"ForeignKey:Id" the result is same. 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)"`
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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