大家星期一早上好!我在预加载实体时遇到了问题!我正在做多个实体的预加载。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
}两个相关的结构(Country和Report)简单地由gorm.Model组成,用于测试目的。
提前感谢你的帮助!!
编辑:我正在使用mysql驱动程序。
附注:[...]表示已隐藏的业务数据,但它们是工作正常的简单列。
发布于 2017-12-04 18:18:55
我刚刚意识到我正在选择与Report表的关系(即FK)为空的查询。
如果关系键不为空,则工作正常。
https://stackoverflow.com/questions/47630962
复制相似问题