Home > Software engineering >  gorm [error] unsupported data type: &map[]
gorm [error] unsupported data type: &map[]

Time:09-09

I want to create an API using map, but when in models I define map type, it error with message not support

This is Model

type Movie struct {
    ID          int            `json:"id" validate:"number"`
    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"`
    MovieGenres map[int]string `json:"-" gorm:"many2many:movie_genres"`
}

type Genre struct {
    ID        int       `json:"-"`
    GenreName string    `json:"genre_name"`
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
}

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

and this is the code to retrieve data by ID

func (MovieRepositoryImpl *MovieRepositoryImpl) GetMovieById(id int) (*Movie, error) {
    var movie Movie
    err := MovieRepositoryImpl.DB.First(&movie, id).Error
    if err != nil {
        return nil, err
    }

    var movie_genres MovieGenre
    rows, err := MovieRepositoryImpl.DB.Model(&movie_genres).Preload(movie_genres.Genre.GenreName).Rows()
    defer rows.Close()

    genres := make(map[int]string)
    for rows.Next() {
        err := MovieRepositoryImpl.DB.ScanRows(rows, &movie_genres).Error

        if err != nil {
            panic(err)
        }
        genres[movie_genres.ID] = movie_genres.Genre.GenreName
    }

    movie.MovieGenres = genres

    return &movie, nil
}

This is my Expect

enter image description here

CodePudding user response:

You can change MovieGenres map[int]string to MovieGenres datatypes.JSONMap

  • Related