42

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.

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

Dave Driesmans
  • 791
  • 1
  • 10
  • 21
  • 3
    You could try specifying the join as being an **left outer join**: `->join('answers as answers', 'responses.answer_id', '=', 'answers.id', 'left outer')`. The last (optional) parameter of the `join` method is `$type`, which when not specified, defaults to the value `inner`. – Bogdan Feb 12 '15 at 15:48
  • @Bogdan This should work. Write it as an answer ;) – lukasgeiter Feb 12 '15 at 17:03
  • @Bogdan, indeed that works! if you put it as answer i can mark it as a correct. weird that it's not better documented here http://laravel.com/docs/4.2/queries#joins. – Dave Driesmans Feb 12 '15 at 20:48
  • There are some missing (albeit not essential) pieces from the Laravel documentation. But if you like to get your hands dirty there's always the possibility to dive into Laravel's source to get a better understanding on how it works. I'll post the solution as an answer for future reference. – Bogdan Feb 12 '15 at 20:53

1 Answers1

77

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 join and left outer join are the same thing, you could just use the leftJoin method instead, to make it more readable:

->leftJoin('answers as answers', 'responses.answer_id', '=', 'answers.id')
Community
  • 1
  • 1
Bogdan
  • 43,166
  • 12
  • 128
  • 129