Search code examples
sqllaravellumen

SQL Postgre to show 1 data if get same some multiple data and how to implement to laravel query


i want to ask about sql in postgresql, i got data from join with 3 table, i got the result but i got multiple data like this image result

and here my sql code in postgresql

select users.* from users inner join model_has_roles on model_has_roles.model_id = users.id 
left join roles on roles.id = model_has_roles.role_id where roles.name not in ('job-seeker') order by users.name asc

how to fix this query where i got the multiple data only 1 data to show.

and i want this sql to implement to laravel query and here my code now

public function getAccountList(){
        $req = app(Request::class);
        // $getAccount = User::query();
        $getAccount = User::join('model_has_roles', function($join) {
            $join->on('users.id', '=', 'model_has_roles.model_id');
        })->leftJoin('roles', function($join){
            $join->on('model_has_roles.role_id', '=', 'roles.id');
        });

        $getAccount->whereNotIn('roles.name', ['job-seeker']);

        if ($q = $req->query('q')) {
            $searchTerm = trim(strtolower($q));
            $getAccount->whereRaw(
                'LOWER(users.name) like (?) or LOWER(users.email) like (?)',
                ["%{$searchTerm}%", "%{$searchTerm}%"]
            );
        }

        // $getAccount->get()->unique('name');
        $getAccount->select(['users.*']);

        $paginator = $this->pagination($getAccount);

        return $this->paginate($paginator, new UserTransformer);
    }

how to fix the query only 1 data to show not the multiple same data. thank you for helping me. God Bless You


Solution

  • use distinct()

    $data = DB::table('test')->[your query builder]->distinct()->get();
    

    Laravel Query Builder Docs

    Just change a bit to make it related to your query builder