我正在使用gorm

我有一个问题,希望有人可以帮助我解决或解释有关此问题的更多信息

type User struct {
    ID        int
    Name      string
    Addresses []Address
}

type Address struct {
    UserID   int `gorm:"index;not null"`
    Address string
    City     string
    Zipcode  int
    Country  string
}

if err := db.Select("name").Preload("Addresses").Find(&users).Error; err != nil {
    // Display error message
} else {
    //
}

结果:
[
    {
      "created_at": "2017-04-02T00:07:59Z",
      "updated_at": "2017-04-02T00:07:59Z",
      "name": "Richard"
    }
  ]

SQL日志:
SELECT * FROM `users` WHERE `users`.deleted_at IS NULL AND ((1 <> 1))

预期结果:
[
  {
    "created_at": "2017-04-02T00:07:59Z",
    "updated_at": "2017-04-02T00:07:59Z",
    "name": "Richard",
    "addresses": [
      {
        "address": "No 1, Street 5",
        "city": "New York",
        "country": "US"
      }
    ]
  }
]

我研究了StackOverflow上的其他文章,但没有找到任何解决方案

最佳答案

选择缺少的id字段,以便不应用预加载。波纹管代码将解决问题

if err := db.Select("id, name").Preload("Addresses").Find(&users).Error; err != nil {
    // Display error message
} else {
    //
}

10-05 22:29