【发布时间】:2021-05-28 20:22:04
【问题描述】:
我想创建一个模型User 和Social,其中User 模型有很多Socials。理想情况下,Social 类型也有一个关系来简化从任一侧的查询。这是一个代码示例:
数据库类型是 MySQL 8.0
type base struct {
ID string `json:"id" gorm:"type:char(36);primaryKey;"`
Created time.Time `json:"created" gorm:"autoCreateTime"`
Updated time.Time `json:"updated" gorm:"autoUpdateTime"`
}
type User struct {
base
Friends []*User `json:"friends" gorm:"many2many:friends"`
Socials []*Social `json:"socials"`
}
type Social struct {
base
Provider string `json:"provider" gorm:"type:varchar(32);index"`
Identifier string `json:"identifier" gorm:"type:varchar(32);index"`
User *User `json:"user" gorm:"foreignKey:ID"`
Token string `json:"token"`
Link string `json:"link" gorm:"type:varchar(128)"`
}
使用db.AutoMigrate(&User{}, &Social{})时出现以下错误:
model.Social's field User, need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface
runtime error: invalid memory address or nil pointer dereference
我试过了:
- 将
gorm:"foreignKey:ID"添加到 User.Socials 标签 - 不使用指针(例如在
UserstructSocials []Social而不是Socials []*Social)
问题依旧
【问题讨论】: