简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM