1 回答

TA貢獻1883條經驗 獲得超3個贊
在您的Post,Map和Element結構中,您具有以下字段:
UserID uint `json:userid`
User User `json:"user"; gorm:"foreignkey:UserID`
您應該User從內容結構中刪除該字段,因為您已經有一個UserID. 在這種情況下,“引用”(ID) 比包括整個用戶對象更明智。如果需要,客戶端可以調用/users/{id}端點并查找更多信息。
還User通過刪除限制結構的內容Maps []Map(負責您提到的循環)。然后您需要設置端點,/user/{id}/maps以便客戶端可以獲取用戶的內容。
這同樣適用于Post和Element。您可以全力以赴只存儲 ID,也可以只存儲一組“子”模型。(地圖嵌入元素,元素不嵌入地圖)。因此,要查找元素的關聯映射,您可以調用 endpoint /maps/{your element's map ID}。Element > Post 相同
type Map struct {
gorm.Model // this takes care of the ID field
UserID uint `json:userid`
Title string `json:title`
Desc string `json: "desc"`
Elements []Element // gorm will handle the relationship automatically
Date time.Time `json: date`
}
type Element struct {
gorm.Model // includes ID
ElementName string `json: element_name`
Desc string `json: desc`
MapID uint `json:mapid`
// Map Map ... This relationship is described by another endpoint - /elements/{elementId}/map to get the related map
Posts []Post // gorm handles this
Date time.Time `json: date`
UserID uint `json:userid`
}
type Post struct {
gorm.Model
Title string `json: p_title`
Subject string `json: subject`
Date time.Time `json: date`
Entry string `json: entry_text`
ElementID uint `json:elementid` // gorm will use this as fk
UserID uint `json:userid`
}
為避免循環,您需要在結構級別使關系成為單向的,并設置更多的 http 路由以朝另一個方向發展(請參閱注釋代碼)。
我描述的是一個簡單的 REST api。微軟有一個很好的概述:https ://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design#organize-the-api-design-around-resources - 特別是客戶/訂單關系你會感興趣的。
在 gorm 方面,您將使用一對多關聯:https ://gorm.io/docs/has_many.html
- 1 回答
- 0 關注
- 89 瀏覽
添加回答
舉報