Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database design for preset/custom choice questions

So I have a HTML form where users can answer single-choice questions either by checkboxing one of the three preset responses, or writing a custom answer of their own.

While this is obviously a many-to-many relationship, I still cannot find a proper way to design database tables so as to handle both types (TEXT and BOOLEAN). My current quick-and-dirty solution is to hard-code a specific choice_id in the junction table for custom answers. I'm looking for a better pattern for this.

like image 498
Mehdi Chibouni Avatar asked Nov 13 '22 21:11

Mehdi Chibouni


1 Answers

Have the following tables:

Table 1:Question

  QuestionID (ID)
  QuestionText (Text) 

Table 2: Question Response

  QuestionResponseId (ID)
  QuestionResponseTypeId (References Question Response Type)
  QuestionResponseDetailsId (References Question Response Details) - This should be used for text only values (Custom Answers)
  QuestionResponse (Boolean) 

Table 3: Question Response Type

  QuestionResponseTypeId (Id)
  Description (Text)  -- Dictates if the answer is a boolean or a text field

Table 4: Question Response Details

   QuestionResponseDetailsId (Id)
   Description (Text) - Holds the text answer to the questions

When the following tables are populated you will have a structure that holds the question, the response of the question (text or boolean).

You could then filter on this to see only text based answers, for example:

SELECT * FROM QuestionResponse
INNER JOIN QuestionResponseDetails ON QuestionResponse.QuestionResponseDetailsId = QuestionResponseDetails.QuestionResponseDetailsId
WHERE QuestionResponse.QuestionResponseTypeId = 1

Where 1 is a Text based answer and 2 is a Boolean based answer (From the Question Response Type Table)

like image 79
Darren Avatar answered Nov 15 '22 12:11

Darren