f1nn
f1nn

Reputation: 7047

How to create self-referenced association field

I'm trying to create self-reference field using gorm:

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

Column post_id is not created in DB. Tried several struct field names, no luck.

Which is the correct way to handle self-refrenced associations?

Thank you.

Upvotes: 0

Views: 1576

Answers (1)

R Menke
R Menke

Reputation: 8391

The Gorm magic isn't in the association (foreign key) part but in the data part.

Gorm will do the sql joins to retrieve the related Post row based on PostID It will then store that data in the nested Post field in Post.

If you only provide Post without PostID Gorm will do nothing as there is no foreign key for it to work with.

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{})

Upvotes: 1

Related Questions