小弟是新人一名, 使用gorm关联数据后, 发现预加载时, 如果外键的值是0, 则无法加载出数据内容. 求解决方案.
代码如下:
```go
type Profile struct {
ID uint `gorm:"primary_key"`
Refer int
Name string
}
type User struct {
gorm.Model
Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
ProfileID int
Username string
}
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
db.AutoMigrate(&Profile{}, &User{})
var pro Profile
pro.ID = 1
pro.Refer = 0
pro.Name = "root"
db.FirstOrCreate(&pro)
pro.ID = 2
pro.Refer = 1
pro.Name = "user"
db.FirstOrCreate(&pro)
pro.ID = 3
pro.Refer = 2
pro.Name = "admin"
db.FirstOrCreate(&pro)
var user User
user.ID = 1
user.ProfileID = 0
user.Username = "张三"
db.FirstOrCreate(&user)
user.ID = 2
user.ProfileID = 1
user.Username = "李四"
db.FirstOrCreate(&user)
user.ID = 3
user.ProfileID = 2
user.Username = "王五"
db.FirstOrCreate(&user)
var users []User
db.Preload("Profile").Find(&users)
for _, user := range users {
fmt.Println(user.Profile)
}
}
```
输出结果:
1. {0 0 } // 正确时, 这里应该是 {1 0 root}
2. {2 1 user}
3. {3 2 admin}
数据库:
![1.png](https://static.golangjob.cn/220426/d0c6a482cfc25c392b0c4686bf03362d.png)
![2.png](https://static.golangjob.cn/220426/b9fb04dbb766f450b29cc979d6a05c4c.png)
有疑问加站长微信联系(非本文作者)