dru5089 2017-04-03 17:43 采纳率: 0%
浏览 302
已采纳

如何在gorm中实现预加载

I'm using gorm.

I have an issue bellow, hope somebody can help me resolve or explain more about that

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 {
    //
}

Result:

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

SQL log:

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

Expect result:

[
  {
    "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"
      }
    ]
  }
]

I have researched some other post on StackOverflow but don't see any solutions

  • 写回答

1条回答 默认 最新

  • doutan1671 2017-04-03 19:48
    关注

    Select missing id fields so preloading was not applied. Bellow code will be resolve issue

    if err := db.Select("id, name").Preload("Addresses").Find(&users).Error; err != nil {
        // Display error message
    } else {
        //
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?