英文:
Go GORM two table requests
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对GORM还不熟悉,我有一个任务,其中涉及到两个表accounts
和users
。
我获取了user.Id
,然后需要从user
表中获取accountId
,然后只需要获取具有与user.AccountId
相同的Id
的账户。
type User struct{
Id int
AccountId int
}
type Account struct{
Id int
Balance int
}
看起来这应该是一个很简单的调用,可以在单个请求中完成,但我找不到一个简单的实现这个逻辑的方法。有人可以帮助我吗?
英文:
So I am new to GORM and I have this task where I have two tables accounts
and users
I get the user.Id
and I need to get the accountId
from the user
table afterwards I need to only get the account that has the same Id
as user.AccountId
type User struct{
Id int
AccountId int
}
type Account struct{
Id int
Balance int
}
It looks like this should be a pretty simple call to do it in a single request, but I can't find a simple implementation for this logic. Can anyone help me
答案1
得分: 1
有多种方法可以实现这个,下面是其中的几种方法。我假设db
变量的类型是*gorm.DB
。此外,下面的代码适用于MySQL(对于PostgreSQL需要进行一些小的更改)。
使用连接仅加载Account数据
var account Account
err := db.Joins("JOIN users ON users.account_id = account.id").Where("users.id = ?", user.Id).First(&account).Error
加载包含Account数据的User对象
这里对User
结构体进行了一些更改,但底层代码更简单。它加载整个User
对象,包括相关的Account
对象。
type User struct{
Id int
AccountId int
Account Account
}
var fullUser User
err := db.Preload("Account").First(&fullUser, user.Id).Error
英文:
There are multiple ways to do this, and below are a couple of them. I'm assuming that the db
variable is of type *gorm.DB
. Also, I'm the code below is suited for MySQL (minor changes are needed for PostgreSQL).
Load just the Account data with joins
var account Account
err := db.Joins("JOIN users ON users.account_id = account.id").Where("users.id = ?", user.Id).First(&account).Error
Load the User object with the Account data
Here there are a few changes to the User
struct, but the underlying code is simpler. Also, it loads the entire User
object, with the related Account
object.
type User struct{
Id int
AccountId int
Account Account
}
var fullUser User
err := db.Preload("Account").First(&fullUser, user.Id).Error
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论