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

How to get data from relation in Laravel used in with()?

我正在从多个相互关联的表中获取数据。但是在其中一个关系中,我想通过 where('user_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'));
}

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

假设您只需要过滤关系而不是 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'));
}

你可以使用深度 with:

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