php – Laravel 4.2 ORM – Querying relation with three table-ThrowExceptions

Exception or error:

I have a database schema that goes like this:

user
  id
  name

question
  id
  title


answer
  id
  answer_text
  user_id
  question_id

Now I want to select all user with all question and user given every question answer.

I am trying with this way:

User Model

public function answer()
{
    return $this->hasMany('answers','user_id','question_id');
}

Answer Model

public function question()
{
    return $this->belongsTo('questions','question_id');
}

Now call from user controller

$user_profile = User::find($userid);

But it gives only user table data and don’t return question and answer.

How to solve:

I think that you can use a has-many-through relation. Since you are using Eloquent, try this example.

Answer´╝Ü

Solution for your question is “EAGER LOADING”, let’s see how we can use it for your situation.

$user_profile = User::with('answer')->find($userid);

this will not give you question from that user, reason is you missing relation between user and question.

Saying above you can get answers and as each answer has relation with question that way you can get question but not ideal way of doing this.

Suggestion
your relations and models are not appropriate it may be enough for what you need but as your application grow you will get into number of issues.

If I would have done this my relations would be different including db structure. For ex:

User: id, name , …..

Question: id, title, …

Answer: id, answer, …

UserQuestion: this should be a pivot table of User & Question [user_id, question_id]

UserAnswer: this should be a pivot table of User & Answer [user_id, answer_id]

QuestionAnswer: this should be a pivot table of Question & Answer [question_id, answer_id]

You can have different scenario of these pivot table you can get away with User_Question_Answer [user_id, question_id, answer_id] but it depeneds on your application needs.

Leave a Reply

Your email address will not be published. Required fields are marked *