select data no repeat in pivot table

妖精的绣舞 提交于 2020-05-16 06:32:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!