Creating records for all tables

Report a typo

Edwin is working with the music SQLite database, below you can see the database diagram:

music database diagram

Edwin is a big fan of the rock band Metallica and wants to insert records of Metallica into the music database. He has already written the code to create and insert an artist record named "Metallica".

Your task is to help Edwin write the additional required code to insert 3 song records into the songs table, and set up GORM's association mode to insert records into the artist_songs join table.

Write a program in Go
package main

import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
"time"
)

// DO NOT modify the model declarations below!
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"`
}

func main() {
db := createDB() // DO NOT delete this line! it creates the in-memory `music` database

artist := Artist{Name: "Metallica"}
db.Create(&artist) // Create the Artist "Metallica"

songs := []Song{
{Title: "Master of Puppets", Duration: 8*time.Minute + 35*time.Second},
{Title: "Enter Sandman", Duration: 5*time.Minute + 31*time.Second},
{Title: "Nothing Else Matters", Duration: 6*time.Minute + 42*time.Second},
}

___

Create a free account to access the full topic