I would like to query for a question and all of its answers. The following two functions work just fine. The problem is I think this should be done in one function, with one query. (I removed error checking for brevity).
func QuestionById(id string) (*Question, error) {
question := new(Question)
_ = db.QueryRow("select * from question where question.id = ?", id).Scan(
&question.Id,
&question.LessonId,
&question.Body,
&question.Type,
)
return question, nil
}
func AnswersByQuestionId(id string) ([]*Answer, error) {
rows, _ := db.Query("select * from answer where question_id = ?", id)
defer rows.Close()
answers := make([]*Answer, 0)
for rows.Next() {
answer := new(Answer)
_ = rows.Scan(&answer.Id, &answer.Body, &answer.QuestionId, &answer.Correct)
answers = append(answers, answer)
}
_ = rows.Err()
return answers, nil
}
I would like to use a join query in this way (or something similar):
func QuestionByIdAndAnswers(id string) (*Question, []*Answer error) {
rows, _ := db.Query("select * from question join answer on question.id = answer.question_id where question.id = ?", id)
// more stuff here
return question, answers, nil
}