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

GORM新手求助:如何通过User.Id单查询获取关联Account数据

用GORM单条查询获取关联的Account数据

已知User.Id,要通过单条SQL查询拿到对应的Account数据,有两种常用的简单实现方式:

方法一:使用JOIN关联查询

直接通过JOIN关联两张表,一次性查询出结果,这是效率最高的方式:

var account Account
// 关联users表,通过User.Id过滤,获取对应的Account数据
db.Joins("JOIN users ON users.account_id = accounts.id").Where("users.id = ?", userId).First(&account)

如果需要同时获取User和Account的完整数据,可以定义一个组合结构体:

type UserAccount struct {
    User
    Account
}

var userAccount UserAccount
db.Joins("JOIN accounts ON accounts.id = users.account_id").Where("users.id = ?", userId).First(&userAccount)

方法二:使用子查询

如果更倾向于分步逻辑的单条查询,可以用子查询先获取AccountId,再查询Account:

var account Account
db.Where("id = (SELECT account_id FROM users WHERE id = ?)", userId).First(&account)

这两种方式都会生成单条SQL语句执行,避免了两次数据库请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:50:24