Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a Left Outer join with Laravel?

Tags:

php

mysql

laravel

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 ?

like image 801
Dave Driesmans Avatar asked Feb 12 '15 15:02

Dave Driesmans


People also ask

How use outer join in laravel?

In Laravel, we can write the following code to represent the above full outer join: $second = DB::table('t2') ->rightJoin('t1', 't1.id', '=', 't2.id') $first = DB::table('t1') ->leftJoin('t2', 't1.id', '=', 't2.id') ->unionAll($first) ->get();

What is left join in laravel?

Laravel itself provide inbuilt method to left join the table like in MySQL or SQL based database we can do join multiple tables using leftJoin function. For example if you have 10 rows and you want the join from other table then it will return the all rows from left table and the matching records from the right table.

Can you do two left outer JOINs?

Yes, it is possible. We would use a query with two LEFT OUTER JOINs to retrieve the hierarchy.


1 Answers

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') 
like image 103
Bogdan Avatar answered Sep 18 '22 15:09

Bogdan