2

In PostgreSQL I have a pretty simple table where I store information about relationships between users and games. Here is a working function which I use to insert data. As you can see it makes multiple SQL queries to the database which is not elegant I think. What do I need to change to insert multiple rows with one query?

var CreateRelationship  = func(responseWriter http.ResponseWriter, request *http.Request) {
    userID := mux.Vars(request)["user_id"]

    type RequestBody struct {
        Games []int `json:"games"`
    }

    requestBody := RequestBody{}

    decoder := json.NewDecoder(request.Body)

    if err := decoder.Decode(&requestBody); err != nil {
        utils.ResponseWithError(responseWriter, http.StatusBadRequest, err.Error())
        return
    }

    for i := 0; i < len(requestBody.Games); i++ {
        if _, err := database.DBSQL.Exec("INSERT INTO users_games_relationship (user_id, game_id) VALUES ($1, $2);", userID, requestBody.Games[i]); err != nil {
            utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
            return
        }
    }

    utils.ResponseWithSuccess(responseWriter, http.StatusOK, "All new records successfully created.")
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

0 Answers0