Skip to content
Advertisement

retrieving multiple records associated to multiple records laravel 4.2

recently i asked this question which got one answer but unfortunately didn’t solve the problem, after that i got no more answers and i really need to fix this problem i have.

Alright so i have to make a quiz website for my school in which a user should be able to play the quiz, this page need to show the quiz name, the questions associated to the quiz and the answers associated to the questions. I can show the quiz name no problem and i can show the questions aswell, but for some reason only the answers associated to the final question are shown.

Here’s my code:

JavaScript

The $id variable is the id of the quiz i selected so i should be able to retrieve all data associated to this id, and all data associated to the associated data of this id.

Here’s my html (with blade):

JavaScript

I know that the problem lies within the way i get my answers from the db but i don’t know how to fix it. Help is much appreciated! Thanks for reading!

*edit,

my db scheme goes as follows:

i have

  • a table called quizzes with an id, name and description.
  • a table called questions with an id, question and a foreign key “quiz_id”
  • a table called answers with an id, answer and a foreign key “question_id”

a quiz can have multiple questions but a question can only have one quiz, a question can have multiple answers but an answer can only have one question.

i hope that is enough information about my database, thanks for helping out!

Advertisement

Answer

You should use Eloquent’s relationships to solve this problem. See more here: http://laravel.com/docs/4.2/eloquent#relationships

The way I see it currently is that you have three models that you’re working with: Quiz, Question and Answer – right?

From your question I gather the following:

  • A Quiz will have many Questions
  • An Answer will belong to one Question

So based on these assumptions I’d flesh out the models as so…

Note:

  • I haven’t used 4.3 for a while so you may need to alter some of the code, but it should be okay
  • Models below assume you are using foreign keys in the manner eloquent expects you too, if not you can define them as the second argument on the relationship method (hasMany, belongsTo)

Quiz.php

JavaScript

Question.php

JavaScript

Answer.php

JavaScript

Then your controller becomes a lot cleaner

Controller

JavaScript

View

JavaScript

Please let me know if you have any trouble implementing the above and I’ll do my best to help out. Relationships can be a bit tricky at first but once you get your head round them you’ll never look back.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement