(Gorm Golang) How to select field without ignore json in struct?

Viewed 32

So, I want to create an API, but when I try to query with a select field, I always fail, I want the data for my API only for the ID and Name fields, I want to remove movies field without ignoring the json because these fields are also needed in other urls, how to solve it?

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"`
    Genres      []Genre   `json:"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"`
    GenreID   int       `json:"genre_id"`
    Genre     Genre     `gorm:"foreignKey:GenreID"`
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
}

This the code for query

func (MovieRepositoryImpl *MovieRepositoryImpl) GetGenres() (*[]Genre, error) {
    var genres []Genre
    err := MovieRepositoryImpl.DB.Find(&genres).Error
    if err != nil {
        return nil, err
    }

    return &genres, nil
}

This the result

I want to remove field movies without ignore json

I want to remove field movies without ignore the json

1 Answers

if you do not want send param: movies to backend and response without moives, it would work, json tag add omitempty.

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