MuscleNerd
MuscleNerd

Reputation: 51

How to create two join tables with go-gorm [Go]

Every time i run AutoMigrate() I get the error level=fatal msg="failed to found relation: UserFriends"

here is my user model

type User struct {
UUID          string         `gorm:"primaryKey;unique;not null" json:"user_id"`
Email         string         `gorm:"unique;not null" json:"email" binding:"required,email"`
Password      string         `gorm:"-:all" json:"password"`
DisplayName   string         `gorm:"unique;not null" json:"display_name" binding:"required"`
FirstName     string         `gorm:"not null" json:"first_name" binding:"required"`
LastName      string         `gorm:"not null" json:"last_name" binding:"required"`
PhoneNumber   string         `gorm:"unique;not null" json:"phone_number" binding:"required"`
DateOfBirth   string         `gorm:"not null" json:"date_of_birth" binding:"required"`
EmailVerified bool           `json:"email_verified"`
PhoneVerified bool           `json:"phone_verified"`
PhotoURL      string         `json:"photo_url" binding:"omitempty,url"`
UpdatedAt     time.Time      `json:"updated_at"`
CreatedAt     time.Time      `gorm:"autoCreateTime" json:"created_at"`
DeletedAt     gorm.DeletedAt `gorm:"index" json:"deleted_at"`
RefreshToken  string         `json:"refresh_token"`
Friendship    []Friendship   `gorm:"many2many:users_friendships;"`

}

here is my friendship model

type Friendship struct {
gorm.Model
FromUserId   string    `gorm:"primaryKey" json:"from_user"`
ToUserId     string    `gorm:"primaryKey" json:"to_user" binding:"required"`
SentTime     time.Time `json:"sent_time"`
ResponseTime time.Time `json:"response_time"`
Accepted     bool      `json:"accepted"`

}

here is my user friend model

type UserFriend struct {
UserUUID     string
FriendshipID uint
Accepted     bool

}

and my migration code

func MigrateDB(db *gorm.DB) error {
err := db.SetupJoinTable(&domain.User{}, "UserFriends", &domain.Friendship{})
if err != nil {
    return err
}

err = db.AutoMigrate(&domain.User{}, &domain.Friendship{}, &joins.UserFriend{})
if err != nil {
    return err
}

return nil

}

Upvotes: 1

Views: 243

Answers (1)

Shahriar Ahmed
Shahriar Ahmed

Reputation: 615

You should use Self Referential Many to Many relationship here. Here is a nice example of user friend relationship.

Upvotes: 1

Related Questions