Your Question

I have two structs one following belongs_to pattern, another reflects this with has_many:

type PostVote struct {
    CreatedAt time.Time `gorm:"index:,sort:desc"`
    UserID    uint      `gorm:"primaryKey;index"`
    User      *User     `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
    PostID    uint      `gorm:"primaryKey;index"`
    Post      *Post     `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}
type Post struct {
...
    PostVotes     []*PostVote
}

This way it makes convenient to define constraints and preload Post into PostVote and reverse: PostVotes for a particular post will be preloaded to Post.

I tried and everything seems working fine. However, I would like to be sure that this is not something unexpected and it won't suddenly break at some moment.

There is nothing in documentation regarding having two relations at the same time: - has_many and belongs_to - has_one and belongs_to

The document you expected this should be explained

https://gorm.io/docs/belongs_to.html https://gorm.io/docs/has_one.html https://gorm.io/docs/has_many.html

Expected answer

I expect that answer is yes, it's ok, and there is nothing wrong, because there are a number of situations where this will be very useful when preloading is actively used with GORM models.

Comment From: ngocketit

The foreign key constraint doesn't work (e.g, not generated in the migration) for me if I use it that way. For example:

type Option struct {
    Base
    Content    string    `gorm:"not null"`
    QuestionID string    `gorm:"not null"`
    Question   *Question `gorm:"constraint:OnDelete:CASCADE;"`
}

type Question struct {
    Base
    Content    string                  `gorm:"not null"`
    Options    []*Option
}

It works if I remove Options []*Option from the Question model

Comment From: inliquid

Thanks, I didn't notice that initially, but I can confirm that in my case constraint on Post field of PostVote struct is also not added. I can see fk_post_votes_user added as expected for User field, and there is also fk_posts_post_votes (instead of fk_post_votes_post) with no actions.

Comment From: inliquid

FYI: moving constraint definition from PostVote to Post seems to solve above problem.