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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With