Search code examples
laravellaravel-query-builder

How to make a distinct in only one table of a join using Laravel Query Builder?


I have this query... and I would like to make a distinct only in (tbl_holdings)

This is my query

$holdings = DB::table('tbl_perimetros')
                ->distinct()
                ->join('tbl_holdings', 'tbl_holdings.id', '=', 'tbl_perimetros.holdings_id')
                ->get();

Solution

  • Use groupBy instead of distinct:

    $holdings = DB::table('tbl_perimetros')
                    ->groupBy('tbl_perimetros.holdings_id') 
                    ->get();
    

    Remove ONLY_FULL_GROUP_BY:

    Add modes to the config/database.php

    'mysql' => [
        ...
        'modes' => [
            'STRICT_ALL_TABLES',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_ZERO_DATE',
            'NO_ZERO_IN_DATE',
            'NO_AUTO_CREATE_USER',
        ],
    ],