【问题标题】:Gorm multiple Preloadings don't workGorm多个预加载不起作用
【发布时间】:2018-05-31 17:01:26
【问题描述】:

大家星期一早上好! 我在预加载实体时遇到问题!我正在对实体进行多次预加载。 Countryentity 工作正常,但 Report 没有被预加载。有什么想法可能导致这种情况吗?

type Review struct {
  ID             int
  Report   Report 'gorm:"ForeignKey:ReportId"'
  ReportId uint
  Country        Country      'gorm:"ForeignKey:CountryId"'
  CountryId      uint
}
func FindApprovedReviews(page int, countryId int) ([]Review, int, error) {
  var reviews [] Review

// Subtract one to fix Offset but keep page number correct
  page -= 1
  err := db.Where("approved_at IS NOT NULL").
//TODO: Change this to a configuration file value
      Limit(10).
      Where("approved_by IS NOT NULL").
      Where("country_id = ?", countryId).
//TODO: Change this (the 10) to a configuration value
      Offset(page * 10).
      Order("id desc").
      Preload("Report").
      Preload("Country").
      Find(&reviews).
      Error
  if err != nil {
      return nil, 0, err
  }

  return reviews, count, err
}

两个相关的结构体(Country 和Report)只是由gorm.Model 组成,用于测试目的。

提前感谢您的帮助!

编辑:我正在使用mysql 驱动程序。

附: [...] 表示已隐藏的业务数据,但它们是可以正常工作的简单列。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    刚刚意识到我正在选择与 Report 表的关系(即 FK)为空的查询。

    如果关系键不为空,则可以正常工作。

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多