我想要一张表中的信息,以及另一张表中是否有匹配的信息。
这是我的代码
$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')。有些回复不匹配(因为没有response.answer_id),但我仍然想要回复信息。
如何在 Laravel 中获得这样的左外连接?
您可以尝试将连接指定为左外连接:
->join('answers as answers', 'responses.answer_id', '=', 'answers.id', 'left outer')
join方法的第四个参数是
$type
,不指定时默认为值inner
。但由于 left join 和 left external join 是 相同的东西,你可以使用 leftJoin
方法来代替,以使其更具可读性:
->leftJoin('answers as answers', 'responses.answer_id', '=', 'answers.id')