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
CodePudding user response:
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
