Laravel检索数据的多种关系

时间:2016-09-09 11:43:30

标签: laravel laravel-5.2

用户有多个问题,有多个用户的问题 问题有多个答案 用户有多个答案 关系在模型中设定。


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

我如何能够检索特定用户对特定问题的回答。

通过这种方式,我可以得到用户的答案和问题:

$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);          
    }
}

这样我就可以得到用户的问题,但问题的所有答案都可以。

$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);
                }                   
            }
        }

但是我遇到了特定用户的问题和特定用户回答问题的麻烦。这样一来 我需要的结果

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
   ...

2 个答案:

答案 0 :(得分:1)

试试这个

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;
                });
            }                   
        }
    }

答案 1 :(得分:1)

你去了

// 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');