开发者

Associating a model twice, CakePHP

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 t开发者_开发知识库est 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?


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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜