【发布时间】:2015-04-13 09:59:05
【问题描述】:
我想要一张表中的信息,如果还有另一张表中的匹配信息。
这是我的代码
$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),但我仍然想要回复信息。
如何在 laravel 中获得这样的左外连接?
【问题讨论】:
-
您可以尝试将连接指定为左外连接:
->join('answers as answers', 'responses.answer_id', '=', 'answers.id', 'left outer')。join方法的最后一个(可选)参数是$type,如果未指定,则默认为值inner。 -
@Bogdan 这应该可以。把它写成答案;)
-
@Bogdan,确实可行!如果您将其作为答案,我可以将其标记为正确。奇怪的是这里没有更好地记录laravel.com/docs/4.2/queries#joins。
-
Laravel 文档中缺少一些(尽管不是必需的)部分。但是,如果你想亲自动手,总有可能深入了解 Laravel 的源代码,以更好地了解它的工作原理。我将发布解决方案作为答案以供将来参考。