【问题标题】:select data no repeat in pivot table在数据透视表中选择不重复的数据
【发布时间】:2020-08-09 21:28:25
【问题描述】:

我有 2 个表和 1 个数据透视表用作历史表,“dateChange”列表示员工所在的商店,因为我使用 Orderby ('dateChange','DESC')。一切正常,但是如何过滤控制器中的结果?没有 REPEAT 记录? 我需要展示属于一家独特商店的所有员工。我再重复一遍:我使用“dateChange”,因为我知道最后一家商店。请帮帮我。谢谢

数据透视表(employee_store)

  • FK_idStore
  • FK_idEmployee
  • 日期变化

表员工

  • idEmployee
  • 姓名

表格存储

  • idStore
  • nameStore
  • 方向

型号

public function employee(){    
   return $this->belongsToMany(employee::class,'employee_store', 'fk_idStore','fk_idEmployee')        
  ->withPivot('dateChange')->orderBy('dateChange','DESC');  

控制器

$store= Store::findOrFail($id)->employee
return $store

【问题讨论】:

    标签: laravel eloquent pivot-table


    【解决方案1】:

    要获取每个商店中每个员工的最后一条记录,请使用:

    public function employee(){
        return Employe_Store::all()->groupBy('fk_idEmployee')->max('dateChange');
    }
    

    【讨论】:

      【解决方案2】:

      你应该使用急切加载:

      在你的控制器中

      $store= Store::findOrFail($id)->with('employee')->get();
      return $store;
      

      更多细节在:

      https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

      【讨论】:

        【解决方案3】:

        你必须改变

        public function employee(){
        return $this->belongsToMany(employee::class,..
        

        public function employees(){
        return $this->belongsToMany(Employee::class,..
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-14
          • 1970-01-01
          • 1970-01-01
          • 2021-10-20
          • 2021-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多