views:

141

answers:

4

I have the following scheme: My site is a trivia game, so every Question "hasMany" Answers, but a Question also "hasOne" correct Answer that is also represented by the Answer model. I have yet to test this, but my programmer's instinct tells me that the retrieved array will be kind of redundant and it will not separate the correct Answer from the rest of them.

My question is, how do I represent this in the models and in the database, is there a better way to represent this relationship?

+1  A: 

Well, I can come up with two ways to do it.

  1. A Question hasMany Answer, while a Question belongsTo a correct Answer (have the answer_id for the correct answer in the question, so it would look like Question(id, answer_id) and Answer(id, question_id))

  2. Have a flag on the answer that reflects if it is the correct one or not.

I think which one to choose is more of a personal opinion, but I would probably go for number 2, even if 1 is more correct out of relational thinking, but it reduces the redundancy and you can still search for it within the answers.

Of course, if a question can have more than one correct answer, then option number 1 is out of the question.

Jimmy Stenke
A: 

Another route would be to create 2 models mapped to the same table. Have a flag in the answer that indicates it is the correct answer or not.

Since you won't be switching which answer is correct then mapping the correctness to a flag at creation time is fine, and will let you have multiple correct answers. With a weighting system you can even value the correctness of the answer.

With two separate models, make sure to set the conditions on the relationships or in the model itself so that the CorrectAnswer model only finds answers with the Answer.correct = true field set. You can then have a generic Answer model that does not have such a condition. Done in the Question model you could even use purely the association flags to fetch both types.

Abba Bryant
A: 

Or just look at this page, very useful ;) http://www.charlesgarwood.com/blog/?p=23

Stefan
This is what really solved my problem, my apologies to Jimmy Stenke, but I prefer a already implemented solution.
ONi
A: 

Try ask at cakeqs.org it is cakephp related portal. But definetely you should just have diferent aliases for both association