Your Question

I have a users table which has a field friends which is a self-referencing many-to-many relationship.

type User struct {
    gorm.Model
    Username    string    `gorm:"unique"`
    Name        string
    Password    string
    Friends     []*User   `gorm:"many2many:user_friends"`
}

When I AutoMigrate the table, the following join table is created:

table: user_friends
    foreign key: user_id, reference: users.id
    foreign key: friend_id, reference: users.id

Now I want to add an extra field, created_at, to the join table. Something like this:

table: user_friends
    foreign key: user_id, reference: users.id
    foreign key: friend_id, reference: users.id
    datetime: created_at

To do this, I follow the documentation's custom join table example, but whenever I SetupJoinTable, the created_at field is missing.

Here is how I am setting up the custom join table:

type Friend struct {
    UserId    int `gorm:"primary_key"
    FriendId  int `gorm:"primary_key"
    CreatedAt time.Time
}
...
err := db.SetupJoinTable(&User{}, "Friends", &Friend{})

How can I make this work?

The document you expected this should be explained

I expected this question to be explained in the many-to-many section of the documentation

Expected answer

I want to be able to add extra fields to a join table created in a many-to-many relationship.

Comment From: pavittarsingh315

I figured it out.

Comment From: nccapo

Hello, i've same issue and here how i solve that.

First you need to create struct according to (Friends []*Usergorm:"many2many:user_friends"``) user_friends name.

type UserFriends struct {
     UserId    int `gorm:"primary_key"
     FriendId  int `gorm:"primary_key"
     CreatedAt time.Time
}

Now you need to call this struct in AutoMigrate.

db.AutoMigrate(UserFriends{})

and it works :))