我获得了包含三个表的PostgreSQL数据库:
\d donators
Column | Type | Nullable
--------------------+--------------------------+----------
id | integer | not null
created_at | timestamp with time zone |
updated_at | timestamp with time zone |
deleted_at | timestamp with time zone |
fname | text |
lname | text |
\d charities
Column | Type | Nullable
--------------------+--------------------------+----------
id | integer | not null
created_at | timestamp with time zone |
updated_at | timestamp with time zone |
deleted_at | timestamp with time zone |
name | text |
funds | numeric |
\d donations
Column | Type | Nullable
--------------------+--------------------------+----------
id | integer | not null
created_at | timestamp with time zone |
updated_at | timestamp with time zone |
deleted_at | timestamp with time zone |
donator_id | integer | not null
charity_id | integer | not null
我需要查询数据库以填充以下Charity结构的一部分(例如[] Charity):
type (
Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
Charity struct {
ID uint `json:"id"`
Name string `json:"name"`
NumberOfDonations uint `json:"number_of_donations"`
TotalFunds float64 `json:"total_funds"`
LastDonator *Person `json:"last_donator"`
}
)
其中“捐赠数量”是捐赠连接表中的捐赠计数,LastDonator是与最新的created_at捐赠相关的人...
我只能使用涉及两个子查询和3个联接的原始SQL查询来执行此操作,然后在Go中进行一些清理。我不希望知道如何设计查询或标记结构,但希望能够使用预加载或关联以更多的GORM方式进行操作。