How to insert a record into an existing has many table with gorm

3.9k views Asked by At

I have two tables

type Podcast struct {
    Id       int
    Title    string
    RssUrl   string `sql:"unique_index"`
    Episodes []Episode
}

type Episode struct {
    Id         int
    PodcastID  int
    Title      string
    Url        string `sql:"unique_index"`
    Downloaded bool
}

I know how to insert episodes into a new podcast like so.

podcast := Podcast{
    Title:    "My Podcast",
    RssUrl:   "http://example.com/feed/",
    Url:      "http://www.example.com",
    Episodes: []Episode{{
        Title:      "Episode One Point Oh!", 
        Url:        "http://www.example.com/one-point-oh", 
        Downloaded: false,
    }},
}

db.Create(&podcast)

How do I go about adding episodes to a podcast that already exists later on?

1

There are 1 answers

0
gregf On BEST ANSWER

I was able to figure it out.

var id int
row := db.Table("podcasts").Where("id = ?", 1).Select("id").Row()
row.Scan(&id)

episode := Episode{
    Title:      "Episode Two!",
    Url:        "http://www.example.com/episode-two",
    Downloaded: true,
    PodcastID:  id,
}

db.Create(&episode)