Search code examples
gomany-to-manyrelational-databasego-gorm

How can I change the column name of a resulting table from many to many in gorm


I already played a lot with Nestjs using TypeORM and now I'm learning to work with Golang and Gorm. I'm rebuilding a system in Nestjs for Go and I'm experiencing a problem when using many2many relations. As I am working with a database already in production and populated, I need to model the struct`s identically to the other project so that there are no problems.

I have two tables that relate in a multiple way, they are playlists and genres and in the database in production they result in the playlists_genres table with the following fields: enter image description here

Note that the fields are like playlistsId and genresId

Already in the project in Golang the result of the m2m of the tables are resulting in: enter image description here

Note that the generated fields are different from what I need, I need to generate identifiers for the database in production, that is playlistsId and genresId.

My relationship code looks like this:

type Playlist struct {
    ID        int32     `json:"id" gorm:"primaryKey;autoIncrement:true"`
    Status    bool      `json:"status" gorm:"not null;default:false"`
    CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;autoCreateTime:milli;type:TIMESTAMP without time zone;default:now();not null"`
    UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at;autoUpdateTime:milli;type:TIMESTAMP without time zone;default:now();not null"`

    Genres        []Genre             `json:"genres" gorm:"many2many:playlists_genres"`
}

and

type Genre struct {
    ID          int32     `json:"id" gorm:"primaryKey;autoIncrement:true"`
    Name        string    `json:"name" gorm:"not null;type:varchar(255)"`

    Playlists    []Playlist         `json:"playlists" gorm:"many2many:playlists_genres"`
}

I've looked a lot and I haven't found a way to change the name of these columns other than manually creating an intermediate table with the columns with the names I need and relating it from one to many.

Could you help me with this? Is it possible to do this without creating a table manually? Thanks!


Solution

  • Unfortunately, I think the only way to achieve your goal is to create a struct called PlaylistGenre and override the names of the columns here.
    With Gorm conventions, you can only act on the ForeignKey constraints created in your database. No chance to override the actual column names of the join table automatically created.
    In your gorm annotation you can use these properties to deal with the foreign keys: foreignKey, references, joinForeignKey, and joinReferences.

    However, you need to use the column, which is impossible here.

    Let me know if you need an example with this approach!