如何与Laravel一起加入左外线?

2022-08-30 12:15:31

我想要一个表的信息,如果有来自另一个表的匹配信息,那也是。

这是我的代码

 $scoreObject = DB::table('responses')
        ->select('responses.id', 'responses.questions_id', 'responses.answer_id', 'responses.open_answer', 'responses.user_id',  'responses.scan_id',
             'questions.question', 'questions.question_nr', 'questions.type', 'questions.totalsection_id',
            'answers.id as answerID', 'answers.answer', 'answers.questions_id', 'answers.points'
        )
        ->Join('answers as answers', 'responses.answer_id', '=', 'answers.id')
        ->Join('questions as questions', 'answers.questions_id', '=', 'questions.id')
        ->orderBy('questions.id', 'ASC')
        ->where('responses.scan_id', $scanid)
        ->where('responses.user_id', $userid)
        ->groupBy('questions.id')
        ->get();

它返回与答案匹配的所有响应(answers.questions_id questions.id”)。有些回复不匹配(因为没有responses.answer_id),但我仍然想要回复信息。

我怎么能在拉拉维尔得到这样一个左外加入?


答案 1

您可以尝试将联接指定为左外联接

->join('answers as answers', 'responses.answer_id', '=', 'answers.id', 'left outer')

join 方法的第四个参数是 ,如果未指定,则默认为 值 。但是由于左连接左外连接一回事,因此您可以改用该方法,以使其更具可读性:$typeinnerleftJoin

->leftJoin('answers as answers', 'responses.answer_id', '=', 'answers.id')

答案 2

推荐