首页 文章

Gorm多个预加载不起作用

提问于
浏览
1

大家周一早上好!我有预加载实体的问题!我正在做多个实体预加载 . Country 实体工作正常,但 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
}

两个相关的结构( CountryReport )仅仅是为了瞄准目的而由 gorm.Model 组成 .

在此先感谢您的帮助!!

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

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

1 回答

  • 1

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

    如果关系键不为null,则工作正常 .

相关问题