Setting up association mode

Report a typo

You are working with the music database. It has three tables: the artists and songs tables and the join table artist_songs:

music database diagram

Below are the declarations of the model structs for the artists and songs tables:

type Artist struct { // Model for the `artists` table
    gorm.Model
    Name  string
    Songs []Song `gorm:"many2many:artist_songs"`
}

type Song struct { // Model for the `songs` table
    gorm.Model
    Title    string
    Duration time.Duration
    Artists  []Artist `gorm:"many2many:artist_songs"`
}

//----------------------------------------------------------------------------------------------------------//

// Retrieve the artist "AC/DC" by its `name`:
artist := Artist{}
db.First(&artist).Where("name = ?", "AC/DC")

// Record for the `songs` table:
song := Song{
    Title:    "Thunderstruck",
    Duration: time.Duration(4*time.Minute + 52*time.Second),
}

Arrange in the correct order the steps to set up GORM's association mode to insert records into the artist_songs join table.

The records that will be inserted must be for the artist with name = "AC/DC" and the song data is within the song struct.
Put the items in the correct order
Call the Model() method with a pointer to the artist model struct
Chain the Association() method and pass to it a string with the "Songs" field
Chain the Append() method with a pointer to the song struct.
___

Create a free account to access the full topic