问题
I have 2 table and 1 pivot table wich I use as table Historical, the column 'dateChange' indicated the store where is the employee, because i use Orderby ('dateChange','DESC'). All is ok, however how can I FILTER the results in my controller? without REPEAT records?. I need to show all the employees that belong to a unique store. I repeat again: I use 'dateChange' for i know the last store. help me, please. Thanks
Pivot Table (employee_store)
- FK_idStore
- FK_idEmployee
- dateChange
Table Employee
- idEmployee
- Name
Table Store
- idStore
- nameStore
- direction
Model
public function employee(){
return $this->belongsToMany(employee::class,'employee_store', 'fk_idStore','fk_idEmployee')
->withPivot('dateChange')->orderBy('dateChange','DESC');
Controller
$store= Store::findOrFail($id)->employee
return $store
回答1:
You have to change
public function employee(){
return $this->belongsToMany(employee::class,..
to
public function employees(){
return $this->belongsToMany(Employee::class,..
回答2:
you should use eager loading:
in your Controller
$store= Store::findOrFail($id)->with('employee')->get();
return $store;
more details in:
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
回答3:
To get the last record of each employee in each store, use:
public function employee(){
return Employe_Store::all()->groupBy('fk_idEmployee')->max('dateChange');
}
来源:https://stackoverflow.com/questions/61440019/select-data-no-repeat-in-pivot-table