How to retrieve parent table using child table in Gorm

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

How to retrieve parent table using child table in Gorm

问题

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

我是Golang的新手,正在面临获取包含父表ID的子表数据的问题。文档中只显示了父表如何使用preload方法获取子表,但没有显示如何获取反向关联的数据。

(一对多关系)
父表:

type User struct {
    Id           uuid.UUID  `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
    Username     string     `json:"username"`
    Password     string     `json:"password,omitempty"`
    Email        string     `json:"email"`
    Gender       string     `json:"gender"`
    Alias        string     `json:"alias"`
    RefreshToken *string    `json:"refresh_token,omitempty"`
    AccessToken  *string    `json:"access_token,omitempty"`
    DateOfBirth  *time.Time `json:"date_of_birth"`
    LastLoggedIn *time.Time `json:"last_logged_in"`
    CreatedAt    time.Time  `json:"created_at"`
    UpdatedAt    time.Time  `json:"updated_at"`
    Account      []Account  `json:"account"`
}

子表:

type Account struct {
    Id        uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
    Name      string    `json:"name"`
    Balance   float32   `json:"balance"`
    UserId    string    `json:"user_id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}

希望返回的JSON数据如下所示:

[{
    "Id":"xxx",
    ....
    "User": {"Id":"xxx"}
}]

我不确定是否可能实现这个功能,但Prisma可以做到。对于打扰你的时间,我表示抱歉,祝你有美好的一天!

英文:

i'm new to Golang and facing retriving child table data that container id refer to parent table id. In the documentation shows that only the parent can retrieve child using preload method but didn't show how to retrieve reversed back.

(one to many relationship)
Parent Table

type User struct {
	Id           uuid.UUID  `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
	Username     string     `json:"username"`
	Password     string     `json:"password,omitempty"`
	Email        string     `json:"email"`
	Gender       string     `json:"gender"`
	Alias        string     `json:"alias"`
	RefreshToken *string    `json:"refresh_token,omitempty"`
	AccessToken  *string    `json:"access_token,omitempty"`
	DateOfBirth  *time.Time `json:"date_of_birth"`
	LastLoggedIn *time.Time `json:"last_logged_in"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	Account      []Account  `json:"account"`
}

Child Table

type Account struct {
	Id        uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
	Name      string    `json:"name"`
	Balance   float32   `json:"balance"`
	UserId    string    `json:"user_id"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Was hoping that can return json like this:

[{
   "Id":"xxx",
   ....
   User: {"Id":"xxx"}
}]

I'm not sure is this possible or not but prisma did it, sorry for disturb your time and have a nice day!

答案1

得分: 1

你可以添加要预加载的字段以及预加载的深度。请查看嵌套预加载

在你的情况下,你可以按照以下方式进行操作。

User字段添加到Account结构体中:

type Account struct {
    Id        uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
    Name      string    `json:"name"`
    Balance   float32   `json:"balance"`
    UserId    string    `json:"user_id"`
    User      *User     `json:"user"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}

在你的方法中:

var users []User

// 预加载User结构体内的Account字段,以及Account结构体内的User字段
err := db.Preload("Account.User").Find(&users).Error
英文:

You can add which fields you want to preload and how deep to go. Check nested preloading.

In your case, you could do it like the below.

add User field to Account struct:

type Account struct {
    Id        uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
    Name      string    `json:"name"`
    Balance   float32   `json:"balance"`
    UserId    string    `json:"user_id"`
    User      *User      `json:"user"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}

in your method:

var users []User

// Preload Account field inside User struct, and User field inside Account struct
err := db.Preload("Account.User").Find(&users).Error

huangapple
  • 本文由 发表于 2023年2月10日 16:26:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408561.html
匿名

发表评论

匿名网友

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

确定