Eloquent chooses the first of each individual 'id'?

I have a staff table with a field district_id. I need a request that selects the first employee from each district.

Currently, I manually hardcode it:

$tributes = [
Employee::where('district_id', '=' 1)->take(1)->get(),
Employee::where('district_id', '=' 2)->take(1)->get(),
Employee::where('district_id', '=' 3)->take(1)->get(),
...
];

Can this be done using only one eloquent call? Any volunteers?

+4
source share
2 answers

I'm not used to laravel. But something like below may help. Group byrequired for one employee, and an ascending ID will confirm the first employee.

Employee::whereIn('district_id', array(1, 2, 3))
            ->orderBy('employee_id', 'asc')
            ->groupBy('employee_id')                
            ->get();
+1
source

try using whereIn in the model

Employee::whereIn('district_id', array(1, 2, 3))->get()
0
source

Source: https://habr.com/ru/post/1569270/