Pietro Bongiovanni
Pietro Bongiovanni

Reputation: 554

Gorm multiple Preloadings don't work

Good Monday Morning everyone! I am having a problem with preloading entities! I am doing multiple preloadings of entities. The Countryentity is working fine, but the Report is not being preloaded. Any ideas what might be causing that?

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
}

The two related structs (Country and Report) are simply made up of gorm.Model for teting purpose.

Thanks in advance for the help!!

EDIT: I am using the mysql driver.

P.S. The [...] represent business data that has been hidden, but they are simple columns that are working fine.

Upvotes: 1

Views: 86

Answers (1)

Pietro Bongiovanni
Pietro Bongiovanni

Reputation: 554

Just realised I was selecting queries where the relation (i.e. FK) with the Report table was null.

Works fine if the relation key is not null.

Upvotes: 1

Related Questions