How to save data with association in gorm golang?

Viewed 47

So, I want to save the movies and movie_genres data, but it always fails, which is stored in the database is the movies table as much as looping movie_genres, and the movie_genres column with the wrong movies ID. This is the result

movies table enter image description here

movie_genres table enter image description here

This the JSON result from frontend

{
   "title":"Qui aut consectetur",
   "release_date":"1974-11-25",
   "runtime":"91",
   "mpaa_rating":"PG",
   "rating":"2",
   "description":
   "Anim dolor molestias",
   "genre_id":["1","2"]
} 

Below is my code on go

models

type Movie struct {
    ID          int          `json:"id"`
    Title       string       `json:"title"`
    Description string       `json:"description"`
    Year        int          `json:"year"`
    ReleaseDate time.Time    `json:"release_date"`
    Runtime     int          `json:"runtime"`
    Rating      int          `json:"rating"`
    MPAARating  string       `json:"mpaa_rating"`
    CreatedAt   time.Time    `json:"created_at"`
    UpdatedAt   time.Time    `json:"updated_at"`
    Genres      []Genre      `json:"genres" gorm:"many2many:movie_genres"`
    MovieGenre  []MovieGenre `json:"movie_genres" gorm:"many2many:movie_genres"`
}

type Genre struct {
    ID        int       `json:"id"`
    GenreName string    `json:"name"`
    Movies    []Movie   `json:"movies" gorm:"many2many:movie_genres"`
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
}

type MovieGenre struct {
    ID        int       `json:"id"`
    MovieID   int       `json:"movie_id"`
    Movie     Movie     `gorm:"foreignKey:MovieID"`
    GenreID   int       `json:"genre_id"`
    Genre     Genre     `gorm:"foreignKey:GenreID"`
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
}

handler.go

func (app *Application) CreateMovies(ctx *gin.Context) {

    var payload web.MoviePayloadResponse
    if err := ctx.BindJSON(&payload); err != nil {
        log.Println(err)
        return
    }

    var movieGenre models.MovieGenre

    movieGenre.Movie.ID, _ = strconv.Atoi(payload.ID)
    movieGenre.Movie.Title = payload.Title
    movieGenre.Movie.Description = payload.Description
    movieGenre.Movie.ReleaseDate, _ = time.Parse("2006-01-02", payload.ReleaseDate)
    movieGenre.Movie.Year = movieGenre.Movie.ReleaseDate.Year()
    movieGenre.Movie.Runtime, _ = strconv.Atoi(payload.Runtime)
    movieGenre.Movie.Rating, _ = strconv.Atoi(payload.Rating)
    movieGenre.Movie.MPAARating = payload.MPAARating
    movieGenre.Movie.CreatedAt = time.Now()
    movieGenre.Movie.UpdatedAt = time.Now()
    
    movieGenre.ID, _ = strconv.Atoi(payload.ID)
    movieGenre.MovieID = movieGenre.Movie.ID
    movieGenre.CreatedAt = time.Now()
    movieGenre.UpdatedAt = time.Now()

    err := app.models.Repository.CreateMovie(movieGenre.Movie)
    if err != nil {
        panic(err)
    }

    
    for _, v := range payload.GenreID {
        movieGenre.GenreID, _ = strconv.Atoi(v)
        err := app.models.Repository.CreateMovieGenres(movieGenre)
        if err != nil {
            panic(err)
        }
    }

    ctx.JSON(http.StatusOK, &gin.H{
        "ok": "response",
    })

    return
}

repository.go

func (MovieRepositoryImpl *MovieRepositoryImpl) CreateMovie(movie Movie) error {
    MovieRepositoryImpl.DB.Create(&movie)
    return nil
}

func (MovieRepositoryImpl *MovieRepositoryImpl) CreateMovieGenres(movieGenre MovieGenre) error {
    MovieRepositoryImpl.DB.Create(&movieGenre)
    return nil
}

payload

type MoviePayloadResponse struct {
    ID          string   `json:"id"`
    Title       string   `json:"title"`
    Description string   `json:"description"`
    Year        string   `json:"year"`
    ReleaseDate string   `json:"release_date"`
    Runtime     string   `json:"runtime"`
    Rating      string   `json:"rating"`
    MPAARating  string   `json:"mpaa_rating"`
    GenreID     []string `json:"genre_id"`
    CreatedAt   string   `json:"created_at"`
    UpdatedAt   string   `json:"updated_at"`
}

The results that I expect are in the movies table, only 1 column is made, and in the movie_genres table store data movies as much as the genre inputted with the new movies ID. How to solve the problem?

0 Answers
Related