You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何预加载非直接关联模型?基于TreatmentFormOutputIndicator预加载OutputIndicators

GORM预加载非直接关联模型及相关场景实现

模型关联修正(先补全GORM关联标签)

首先需要为模型添加GORM关联标签,让框架识别关联关系,否则预加载无法生效:

type TreatmentFormOutput struct {
    ID              uint
    OutputID        uint
    Output          Output `gorm:"foreignKey:OutputID"` // 一对一关联Output
    TreatmentFormID uint
    // 多对多关联OutputIndicator,通过中间表treatment_form_output_indicators
    Indicators      []OutputIndicator `gorm:"many2many:treatment_form_output_indicators;joinForeignKey:TreatmentFormOutputID;joinReferences:OutputIndicatorID"`
}

type Output struct {
    ID uint
}

type OutputIndicator struct {
    ID       uint
    OutputID uint `gorm:"foreignKey:OutputID"` // 关联Output
}

type TreatmentFormOutputIndicator struct {
    ID                    uint
    TreatmentFormOutputID uint
    TreatmentFormOutput   TreatmentFormOutput `gorm:"foreignKey:TreatmentFormOutputID"` // 关联TreatmentFormOutput
    OutputIndicatorID     uint
    OutputIndicator       OutputIndicator `gorm:"foreignKey:OutputIndicatorID"` // 关联OutputIndicator
    LevelTarget           int
    LevelStart            int
    LevelEnd              int
}

1. 预加载非直接关联的模型

如果需要加载跨层级的非直接关联(比如从TreatmentFormOutput加载其Indicators关联的Output),可以使用嵌套预加载,通过链式调用Preload实现:

var treatmentFormOutputs []TreatmentFormOutput
// 预加载Indicators,同时预加载每个Indicator关联的Output
db.Preload("Indicators.Output").Find(&treatmentFormOutputs)

如果需要自定义过滤条件,可在Preload中传入回调函数:

db.Preload("Indicators", func(db *gorm.DB) *gorm.DB {
    // 仅加载OutputID大于0的Indicator
    return db.Where("output_id > ?", 0)
}).Preload("Indicators.Output").Find(&treatmentFormOutputs)

2. 基于TreatmentFormOutputIndicator预加载TreatmentFormOutput中的OutputIndicators

先确保TreatmentFormOutputIndicator已关联TreatmentFormOutput,然后使用嵌套预加载直接穿透到目标关联:

var tfIndicators []TreatmentFormOutputIndicator
// 预加载关联的TreatmentFormOutput,同时加载该TreatmentFormOutput下的所有OutputIndicators
db.Preload("TreatmentFormOutput.Indicators").Find(&tfIndicators)

同样支持添加过滤条件,比如只加载目标值大于50的Indicator:

db.Preload("TreatmentFormOutput.Indicators", func(db *gorm.DB) *gorm.DB {
    return db.Where("level_target > ?", 50)
}).Find(&tfIndicators)

内容的提问来源于stack exchange,提问作者zexceed12300

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 13:45:57