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

如何用单个结构体替换GORM Select语句中的指定字段列表?

用结构体替代GORM Select语句中的字段文本

你可以通过定义包含所需查询字段的结构体,结合GORM的gorm:"column:xxx"标签映射数据库列,来替代手写的Select字段列表。具体操作如下:

1. 定义目标结构体

针对你要查询的ag_anchor和ag_apply_record表字段,定义一个结构体,给每个字段加上明确的列映射标签,区分同名字段(比如id、name):

// 定义包含跨表字段的结构体
type ApplyWithAnchor struct {
    AnchorID   uint    `gorm:"column:anchor.id"` // 对应join语句中ag_anchor的别名anchor的id列
    AnchorName string `gorm:"column:anchor.name"`
    ApplyID    uint    `gorm:"column:ag_apply_record.id"`
    ApplyName  string `gorm:"column:ag_apply_record.name"`
    Price      float64 `gorm:"column:ag_apply_record.price"`
}

注:因为你在Joins里给ag_anchor起了别名anchor,所以标签里用anchor.id比ag_anchor.id更简洁,两者效果一致。

2. 改写GORM查询代码

直接将Select的参数换成结构体指针,GORM会自动解析结构体标签生成对应的字段查询语句:

var data []ApplyWithAnchor
db.Table(model.TableName()).
    Select(&ApplyWithAnchor{}).
    Joins("left join ag_anchor anchor on anchor.id = ag_apply_record.anchor_id").
    Find(&data, "user_id = ?", userID)

可选:嵌套结构体写法

如果想按表维度拆分字段,也可以用嵌套结构体,同样需要指定列映射标签:

type AnchorInfo struct {
    ID   uint   `gorm:"column:anchor.id"`
    Name string `gorm:"column:anchor.name"`
}

type ApplyRecordInfo struct {
    ID    uint    `gorm:"column:ag_apply_record.id"`
    Name  string  `gorm:"column:ag_apply_record.name"`
    Price float64 `gorm:"column:ag_apply_record.price"`
}

type ApplyWithAnchor struct {
    AnchorInfo
    ApplyRecordInfo
}

查询时依然使用Select(&ApplyWithAnchor{})即可,效果和单个结构体一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:01:11