Home > Net >  gorm: define a valid foreign key for relations or implement the Valuer/Scanner interface
gorm: define a valid foreign key for relations or implement the Valuer/Scanner interface

Time:02-17

I want to add some foreign keys to my models in gorm. I've done exactly the same as the documentation for adding foreign keys. these are the models

Album model:

type Album struct {
    gorm.Model
    Artists     []Artist
    Name        string
    ReleaseDate time.Time
    Genre       Genre
    Picture     string
}

Artist model:

type Artist struct {
    gorm.Model
    Name        string
    Description string
    YearsActive string
}

Genre model:

type Genre struct {
    gorm.Model
    Name        string
    Description string
}

Track model:

type Track struct {
    gorm.Model
    Album    Album
    Name     string
    Artists  []Artist
    Playtime time.Duration
}

and the code I'm using for creating tables:

DB.Debug().AutoMigrate(&models.Genre{}, &models.Artist{}, &models.Album{}, &models.Track{})

what am I doing wrong here? I'm new to the foreign key concept. I just want to associate tracks with their artists and albums respectively.

CodePudding user response:

So, the issue is that gorm does not know how to connect album with artist (same for others), you need to add AlbumID field to Artist struct in order for gorm to know what is the connection between structs..

Here is the example for all structs that you presented:

Album model:

type Album struct {
    gorm.Model
    Artists     []Artist `gorm:"many2many:album_artists;"`
    Name        string
    ReleaseDate time.Time
    GenreID     uint
    Genre       Genre
    Picture     string
}

Since album and artist is many-to-many relationship, you may back-reference it depending on your needs check here

Artist model:

type Artist struct {
    gorm.Model
    Name        string
    Description string
    YearsActive string
}

Genre model:

type Genre struct {
    gorm.Model
    Name        string
    Description string
}

Track model:

type Track struct {
    gorm.Model
    AlbumID  uint
    Album    Album
    Name     string
    Artists  []Artist  `gorm:"many2many:track_artists;"`  // you may back reference this too
    Playtime time.Duration
}

And now you can use this:

DB.Debug().AutoMigrate(&models.Genre{}, &models.Artist{}, &models.Album{}, &models.Track{})
  • Related