gorm 分页关联无效

# 车辆
type Vehicle struct {
        ID            int32      `json:"id" gorm:"primary_key"`
        Departure     int32      `json:"departure" form:"departure" gorm:"column:departure"`
        CreatedAt     time.Time  `json:"-" form:"-" gorm:"column:created_at"`
        UpdatedAt     time.Time  `json:"-" form:"-" gorm:"column:updated_at"`
        DeletedAt     *time.Time `json:"-" form:"-" gorm:"column:deleted_at"`

        Region Region `json:"region" gorm:"foreignkey:ID;AssociationForeignKey:Departure"`
    }

# 城市
type Region struct {
    ID              int32  `json:"id" gorm:"primary_key"`
    Pid             int32  `json:"pid" form:"pid" gorm:"column:pid"`
    Name            string `json:"name" form:"name" gorm:"column:name"`
}

执行分页查询

var count uint64
list := make([]*models.ContactVehicle, 0)
db.Where("departure = ?",form.Departure).Order("id desc").Find(&list).Limit(page).Offset((page - 1) * size).Count(&count)

最终关联无效,请问问题出在哪里?

已邀请:

lrita

赞同来自:

分拆成,问题出在哪,自己看源码实现。

db.Model(&models.ContactVehicle{}).Where("departure = ?",form.Departure).Count(&count)

db.Where("departure = ?",form.Departure).Order("id desc").Limit(size).Offset((page - 1) * size).Find(&list)

jss_cn

赞同来自:

解决了,没仔细看文档,关联有好几种方法: 我选用 Preload

db.Model(&models.ContactVehicle{}).Where("departure = ?",form.Departure).Count(&count)
db.Where("departure = ?",form.Departure).Order("id desc").Preload("Region").Limit(size).Offset((page - 1) * size).Find(&list)

要回复问题请先登录注册