How to remove duplicates from 2 joins in laravel?

Member

by denis , in category: PHP Frameworks , 5 months ago

How to remove duplicates from 2 joins in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a month ago

@denis 

In Laravel, you can remove duplicates from 2 joins by using the selectRaw() method along with the groupBy() method.


Here is an example of how you can remove duplicates from 2 joins in Laravel:

1
2
3
4
5
$data = DB::table('table1')
    ->join('table2', 'table1.id', '=', 'table2.table1_id')
    ->join('table3', 'table2.id', '=', 'table3.table2_id')
    ->selectRaw('DISTINCT table1.id, table1.column1, table2.column2, table3.column3')
    ->get();


In this example, we are selecting only distinct records based on the table1.id column. You can customize the columns you want to select and apply the DISTINCT keyword to remove duplicates.


Remember to replace table1, table2, and table3 with your actual table names and the column names accordingly.