2017-10-21 140 views
0

我試圖創建一個使用gorm自我參照場:如何創建自引用關聯領域

type Post struct { 
    ID  uint  `gorm:"primary_key" json:"id"` 
    Post  *Post  `json:"post" xml:"post" sql:"default:null"` 
} 
db.AutoMigrate(&Post{}) 

列不在DB創建post_id。嘗試了幾個結構字段名稱,沒有運氣。

哪個是正確的方式來處理自我refrenced協會?

謝謝。

回答

1

Gorm魔術不在關聯(外鍵)部分,而是在數據部分。

格姆會做的SQL連接以獲取基於PostID相關Post行,然後將這些數據存儲在嵌套Post領域Post

如果您只提供Post而沒有PostID Gorm將不做任何事情,因爲沒有外鍵可以使用。

type Post struct { 
    ID  uint  `gorm:"primary_key" json:"id"` 
    Post  *Post  `json:"post" xml:"post" sql:"default:null"` 
    PostID uint  `json:"post_id" xml:"post_id"` 
} 
db.AutoMigrate(&Post{})