去GORM两个表请求

huangapple go评论75阅读模式
英文:

Go GORM two table requests

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对GORM还不熟悉,我有一个任务,其中涉及到两个表accountsusers

我获取了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

huangapple
  • 本文由 发表于 2022年9月7日 21:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/73636011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定