Php 如何从with()中使用的Laravel中的关系中获取数据?

Php 如何从with()中使用的Laravel中的关系中获取数据?,php,laravel,eloquent,relationship,Php,Laravel,Eloquent,Relationship,我从多个相互关联的表中获取数据。但是在其中一个关系中,我想通过where('user\u id,$userID)获取userAnswers记录。它的正确语法是什么 public function survey_completed_show($userSurvey, $userID) { $userSurvey = UserSurvey::with('survey.questions.userAnswers')->find($userSurvey); return vie

我从多个相互关联的表中获取数据。但是在其中一个关系中,我想通过
where('user\u id,$userID)
获取
userAnswers
记录。它的正确语法是什么

public function survey_completed_show($userSurvey, $userID)
{
    $userSurvey =  UserSurvey::with('survey.questions.userAnswers')->find($userSurvey);

    return view('surveys.conducted-answers', compact('userSurvey'));
}

我只想获取所选用户的答案,我目前正在获取每个用户的所有答案

假设您只需要过滤关系,而不需要用户调查,您可能想试试这个

public function survey_completed_show($userSurvey, $userID)
{
    $userSurvey =  UserSurvey::with(['survey.questions.userAnswers' => function($q) use ($userID){
        $q->where('user_id', $userID);
    }])->find($userSurvey);

    return view('surveys.conducted-answers', compact('userSurvey'));
}

您可以将deep
一起使用:

$userSurvey =  UserSurvey::with(['survey'=>function($query)use( $userID){
            $query->with(['questions'=>function($query)use( $userID){
                    $query->with(['userAnswers'=>function($query)use( $userID){
                        $query->where('user_id', $userID);
                    }]);
            }]);
            }])->find($userSurvey);

是的,这是你解决的另一个问题。深新对我来说是新的谢谢