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

Gorm中Raw()结合Preload()的实现及链式调用预加载失效问题

问题:Gorm预加载关联表数据失败

项目开发中因复杂查询需求,先使用Gorm的Raw()方法编写原生SQL,需要获取与tbl1.type_id关联的记录,但在Raw()前添加Preload()后未生效,存储结果的结构体数组中Type字段始终未填充。

【更新】后续将原生SQL转为Gorm链式调用,查询功能与原Raw()效果一致,但预加载关联表actuator_types仍然无效。已添加Preload()语句、对应的Joins()关联,且通过Model()指定了主表,但结果中关联数据仍未填充,需解决该问题。


原始Raw()查询SQL

SELECT tbl1.id, tbl1.some_name, tbl5.some_status, tbl1.some_tbl2_id, tbl1.type_id, tbl1.created_at, tbl5.name
FROM table1 tbl1
JOIN table2 tbl2 ON tbl1.some_tbl2_id = tbl2.id
JOIN table3 tbl3 ON tbl3.edge_device_info_id = tbl2.id
JOIN table4 tbl4 ON tbl4.id = tbl3.account_id
LEFT JOIN table5 tbl5 ON tbl5.tbl1_id = tbl1.id
WHERE tbl5.tbl1_id IS NULL OR tbl5.updated_at = (
    SELECT MAX(updated_at)
    FROM table5
    WHERE tbl1_id = tbl1.id
)
ORDER BY tbl1.created_at ASC;

转为Gorm链式调用后的代码

Model(models.ActuatorDeviceInfo{}).Preload("ActuatorDeviceInfo.Type").
Select("actuator_device_infos.*, actuator_device_infos.id, at.*").
Joins("JOIN edge_device_infos edi ON actuator_device_infos.parent_edge_device_id = edi.id").
Joins("JOIN user_owned_edge_devices ae ON ae.edge_device_info_id = edi.id").
Joins("JOIN accounts acc ON acc.id = ae.account_id").
Joins("JOIN actuator_types at ON at.id = actuator_device_infos.type_id").
Joins("LEFT JOIN actuator_updates au ON au.actuator_device_info_id = actuator_device_infos.id").
Where("au.actuator_device_info_id IS NULL OR au.updated_at = (?)",
    helpers.GetDB().Model(&models.ActuatorUpdate{}).Select("MAX(updated_at)").
    Where("au.actuator_device_info_id = actuator_device_infos.id")).
Order("actuator_device_infos.created_at DESC").
Scan(&actuator_device_infos)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:53:12