php 如何使用 Laravel 进行左外连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28481321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:53:12  来源:igfitidea点击:

How to do a Left Outer join with Laravel?

phpmysqllaravel

提问by Dave Driesmans

i want information from one table and if there is matched info from another table that as well.

我想要一张桌子上的信息,如果有来自另一张桌子的匹配信息。

this my code

这是我的代码

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

It returns all responses that have matches with answers (answers.questions_id questions.id'). some responses don't have matched (because there is no responses.answer_id) but i still want the responses info then.

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

how can i get such a left outer join in laravel ?

我怎样才能在 Laravel 中获得这样的左外连接?

回答by Bogdan

You could try specifying the join as being a left outer join:

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

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

The fourth parameter of the join method is $type, which when not specified, defaults to the value inner. But since left joinand left outer joinare the same thing, you could just use the leftJoinmethod instead, to make it more readable:

join 方法的第四个参数是$type,当未指定时,默认为 value inner。但是由于left joinleft outer join一回事,你可以改用该leftJoin方法,使其更具可读性:

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