我想要来自一个表的信息,以及是否还有来自另一个表的匹配信息。
这是我的代码
$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')。一些回复没有匹配(因为没有respond.answer_id),但我仍然想要回复信息。
如何在laravel中获得这样的左外连接?
答案 0 :(得分:50)
您可以尝试将联接指定为左外连接:
->join('answers as answers', 'responses.answer_id', '=', 'answers.id', 'left outer')
连接方法的第四个参数是$type
,未指定时,默认值为inner
。但由于左连接和左外连接为the same thing,您可以使用leftJoin
方法,以使其更具可读性:
->leftJoin('answers as answers', 'responses.answer_id', '=', 'answers.id')