Как сделать вложенный JSON-ответ в Go? - PullRequest
0 голосов
/ 04 марта 2019

Я новичок в Go и мне нужна помощь.

В моей базе данных PostgreSQL у меня 4 таблицы.Они назвали: surveys, questions, options и surveys_questions_options.

Они выглядят так:

surveys таблица:

| survey_id (uuid4)                    | survey_name (varchar) |
|--------------------------------------|-----------------------|
| 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | April                 |
| b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | May                   |

questions таблица:

| question_id (int) | question_text (text)         |
|-------------------|------------------------------|
| 1                 | What is your favorite color? |

options таблица:

| option_id (int)   | option_text (text) |
|-------------------|--------------------|
| 1                 | red                |
| 2                 | blue               |
| 3                 | grey               |
| 4                 | green              |
| 5                 | brown              |

surveys_questions_options таблица объединяет данные из всех трех предыдущих таблиц:

| survey_id                            | question_id | option_id |
|--------------------------------------|-------------|-----------|
| 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | 1           | 1         |
| 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | 1           | 2         |
| 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | 1           | 3         |
| b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | 1           | 3         |
| b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | 1           | 4         |
| b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | 1           | 5         |

Какя могу сделать вложенный ответ JSON в Go?Я использую библиотеку GORM.Мне нужен ответ в формате JSON, такой как:

[
    {
        "survey_id": "0cf1cf18-d5fd-474e-a8be-754fbdc89720",
        "survey_name": "April",
        "questions": [
            {
                "question_id": 1,
                "question_text": "What is your favorite color?",
                "options": [
                    {
                        "option_id": 1,
                        "option_text": "red"
                    },
                    {
                        "option_id": 2,
                        "option_text": "blue"
                    },
                    {
                        "option_id": 3,
                        "option_text": "grey"
                    },
                ]
            }
        ]
    },
    {
        "survey_id": "b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720",
        "survey_name": "May",
        "questions": [
            {
                "question_id": 1,
                "question_text": "What is your favorite color?",
                "options": [
                    {
                        "option_id": 3,
                        "option_text": "grey"
                    },
                    {
                        "option_id": 4,
                        "option_text": "green"
                    },
                    {
                        "option_id": 5,
                        "option_text": "brown"
                    },
                ]
            }
        ]
    }
]

Мои модели выглядят так:

type Survey struct {
  SurveyID string `gorm:"primary_key" json:"survey_id"`
  SurveyName string `gorm:"not null" json:"survey_name"`
  Questions []Question 
}

type Question struct {
  QuestionID int `gorm:"primary_key" json:"question_id"`
  QuestionText string `gorm:"not null;unique" json:"question_text"`
  Options []Option
}

type Option struct {
  OptionID   int    `gorm:"primary_key" json:"option_id"`
  OptionText string `gorm:"not null;unique" json:"option_text"`
}

Ответы [ 3 ]

0 голосов
/ 04 марта 2019

Мы упускаем некоторую область видимости из вашего кода, и поэтому довольно сложно указать вам правильное направление.Вы спрашиваете о запросе GORM, чтобы вы получили []Survey, или вы спрашиваете о сортировке []Survey?В любом случае, вы также должны добавить тег к Вопросам, как ответил Slomek.

0 голосов
/ 16 августа 2019

Однако попробуйте это: получить вложенные данные в м2м соотношении

type Survey struct {
  gorm.Model
  SurveyID string       `gorm:"primary_key" json:"survey_id"`
  SurveyName string     `gorm:"not null" json:"survey_name"`
  Questions []*Question `gorm:"many2many:survey_questions;"`
}

surveys := []*model.Survey{}
db := dbSession.Where(&model.Survey{SurveyID: id}).Preload("Questions").Find(&surveys)
0 голосов
/ 04 марта 2019

Я не уверен, что о нашей части GORM, но с JSON вам нужно добавить теги struct и для вложенных объектов:

type Survey struct {
  ...
  Questions []Question `json:"questions"`
}

type Question struct {
  ...
  Options []Option `json:"options"`
}
...