Solution for How to add another table after joining multiple tables in Laravel?
is Given Below:
I’m trying to achieve the following MySQL query with Laravel
SELECT a.* , b.* , c.* FROM table_1 a LEFT JOIN table_2 b ON a.b_id = b.id , table_3 c WHERE c.age > 21;
I know how to join tables in Laravel. But if you see my SQL query carefully you can find that there is another table just after the left join (without any join). This is where I’m stuck.
I tried the following code in Laravel, but didn’t work.
DB::table(DB::raw('table_1 a, table_3 c')) ->select('a.*', 'b.*', 'c.*') ->leftJoin('table_2 b', 'a.b_id', '=', 'b.id') ->where('c.age', '>', 21) ->get();
Please help me out with the proper solution. Thanks in advance.
Note: Please ignore syntax error if any
DB::table('a') ->leftJoin('b', 'a.b_id', '=', 'b.id') ->leftJoin('c', 'a.c_id', '=', 'c.id') ->select('a.*', 'b.*', 'c.*') ->get();
what you are missing is left join relation for c table, I mean this -> c.id = a.c_id
also because you are selecting everything from each table you will get errors such as ID is ambiguous, this is because both or in this case all three tables have id column, same goes for all columns that have the same name in any of the three tables. You need to be more specific in your select statement of what is it that you want to select, and if it has the same column name, then alias it like so
->select('a.id as a_id'); or
->select('b.something as something');