Laravel-从多对多关系中检索记录

时间:2019-04-15 14:39:36

标签: php laravel

我在多对多关系中拥有三个表

"aggregations": {
    "aads": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "aa",
          "doc_count": 1
        },
       {
          "key": "bb",
          "doc_count": 1
        }
      ]
    },
    "count": {
      "value": 2
    }
  }

部门表

┌─────────────────┐          ┌─────────────────┐          ┌──────────────────┐
│ users           │          │ department_user │          │ departments      │
├─────────────────┤          ├─────────────────┤          ├──────────────────┤
| id              |          | id              |          | id               |
| name            |          | user_id         |          | name             |
└─────────────────┘          | department_id   |          └──────────────────┘
                             | joined_at       |          
                             └─────────────────┘          

用户表

1 | department 1
2 | department 2
3 | department 3

部门用户表

1| Mark
2| Jack

用户模型:

Id | user_id | department_id | joined_at
1  |    1    |      1        | 2019-01-01 
2  |    2    |      1        | 2019-03-26
3  |    1    |      1        | 2019-04-01
4  |    1    |      3        | 2019-05-01

部门模型:

public function departments()
{
   return $this->belongsToMany('App\Department)->withPivot('joined_at');
}

DepartmentController:

public function users()
{
   return $this->belongsToMany('App\User')->withPivot('joined_at');
}

Show.blade:

$department = Department::with(['phones', 'users' => function($query)
{
  $query->orderBy('joined_at', 'desc');
}])->get();
return view('dashboard.departments.show', compact('department'));

我想要列出这样的用户

部门1

<h3>{{  department->name }}</h3><span>{{ $department->users->count() }}</span>
@foreach ($department->users as $user)
   <li>
      {{ $user-> name }} 
      {{ $user-> departments->last()->pivot->joined_at }}
   </li>
 @endforeach

部门3

1 users
Jack  –   joined_at 2019-03-26

但是我得到的结果是

部门1

1 users
Mark   –   joined_at 2019-05-01

部门3

3 users
Mark   –   joined_at 2019-01-01
Jack  –   joined_at 2019-03-26
Mark   –   joined_at 2019-04-01

因此,我想列出某个部门中的最后一个用户并对其进行计数,但是如果用户以前的日期在该部门中,则忽略重复项

3 个答案:

答案 0 :(得分:0)

如果您希望多对多关系没有重复,只需从Id表中删除department_user列,然后将表的主键设置为user_iddepartment_id的组合。

这将使您避免将来重复。

答案 1 :(得分:0)

尝试一下

Department::join('department_user','department_user.department_id','=','departments.id')
->join('users', 'users.id', '=', 'department_user.user_id')
->selectRaw('users.id, COUNT(*) AS count, MAX(joined_at) AS joined_at')
->groupBy('department_user.user_id')
->having('count', '<', 2)  // ignore duplicates
->orderBy('joined_at', 'desc')
->get();

答案 2 :(得分:0)

      DefaultTableModel model = (DefaultTableModel) tabela.getModel();
        String path="";
        JFileChooser j= new JFileChooser();
       j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      j.showSaveDialog(this);
          int x=j.showOpenDialog(this);

          if(x==JFileChooser.APPROVE_OPTION){
 path=j.getSelectedFile().getPath();
 }

 Document doc= new Document();
    try {
        PdfWriter.getInstance(doc, new FileOutputStream(path+"raport.pdf"));
        doc.open();
        PdfPTable tbl=new PdfPTable(4);
        tbl.addCell("column1");
        tbl.addCell("column2");
        tbl.addCell("column3");
        tbl.addCell("column4");

        for(int i=0; i<table.getRowCount(); i++){
            String column1=table.getValueAt(i, 0).toString();
            String column2=table.getValueAt(i, 1).toString();
            String column3=table.getValueAt(i, 2).toString();
            String column4=table.getValueAt(i, 3).toString();

            tbl.addCell(column1);
            tbl.addCell(column2);
            tbl.addCell(column3);
            tbl.addCell(column4);
        }
         doc.add(tbl);
    }
    catch (FileNotFoundException ex){
    Logger.getLogger(Energy.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(Energy.class.getName()).log(Level.SEVERE, null, ex);
    }

并且在循环部门之前

$department = Department::with(['phones', 'users' => function($query)
{
$query->orderBy('joined_at', 'desc');
}])->get();