Steve
Steve

Reputation: 1672

Laravel manytomany relationships retrieving data

Users have multiple questions and questions have multiple users.
Questions have multiple answers.
Users have multiple answers.
Relations are set in model.

tables:

questions --> id   question
answers --> id q_id user_id answer
users --> id email username
question_user --> user_id q_id

How can i retreive the answer given by particular user of the particular question.

this way i can get the answers and questions of the user:

$users=User::where(['id'=>1])->with('questions','answers')->get(); 
foreach($users as $user)
{
    foreach($user->questions as $question)
    {
        echo "<pre>";print_r($question->question);                      
    }

    foreach($user->answers as $answer)
    {
        echo "<pre>";print_r($answer->answer);          
    }
}

and this way i can get the questions of the user but all answers of the questions.

$users=User::where(['id'=>1])->with('questions','answers')->get(); 
        foreach($users as $user)
        {
            foreach($user->questions as $question)
            {
                echo "<pre>";print_r($question->question);  
                foreach($question->answers as $answer)
                {
                    echo "<pre>";print_r($answer->answer);
                }                   
            }
        }

But i am having the trouble of getting the question of the particular user and answer of the question by particular user. this way
Results i need

user id=1.
question 1
answer by user id 1.
question 2
answer by user id 1
...



 user id=2.
 question 1
 answer by user id 2.
 question 2
 answer by user id 2
   ...

Upvotes: 0

Views: 68

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

there you go

// User model
public function answeredQuestions()
{
  return $this->belongsToMany(Question::class, 'answers', 'user_id', 'question_id');
}

// then
$user->answeredQuestions()->find($question_id)->pivot->answer;

// or to make it 'safe' - no Trying to get property on non-object if no answer is found
data_get($user->answeredQuestions()->find($question_id), 'pivot.answer');

Upvotes: 1

user259947
user259947

Reputation: 59

try this

foreach($users as $user)
    {
        foreach($user->questions as $question)
        {
            echo "<pre>";print_r($question->question);  
            foreach($question->answers as $answer)
            {
                  echo "<pre>";print_r($answer->filter(function ($answer) use ($user) {
                    return $answer->user_id== $user->id;
                });
            }                   
        }
    }

Upvotes: 1

Related Questions