首页 > 解决方案 > 在laravel中获取一个标题下相同字符串的所有记录

问题描述

我目前正在通过在 laravel 中使用 join 从多个表中获取记录。但我的问题是,在教师姓名下的所有记录都会显示那些具有相同教师姓名的其他人应该在下一张表中,例如

Teacher1 name
id    name       class    subject
1     student1    8         chem 
2     student2    9         phy 
teacher2 name
3     student3    9         chem 
4     student4    11        chem 
teacher3 name
......

这是我的 laravel 视图

<table class="table">
      <thead>
       @foreach($students as $student)
        <tr style="background-color: #e9e5e4;">
          <td colspan="4">{{$student->teacher_name}}</td>
        </tr>
      <tr>
        <th>Name</th>
        <th>Class</th>
        <th>Subject</th>
      </tr>
      </thead>
      <tbody>
        <tr>
          <td>{{$student->name }}</td>
          <td>{{$student->class}} </td>
          <td>{{$student->subject }} </td>
        </tr>
      @endforeach
      </tbody>
    </table>

但是根据上面的代码,如果在数据库中发现重复条目​​,我有多个问题,例如教师姓名重复,并且我不能使教师姓名唯一,因为我需要多个相同姓名的条目,其次所有记录都显示在每个教师下面。我目前的输出是这样的

Teacher1 name
    id    name       class    subject
    1     student1    8         chem 
    2     student2    9         phy 
    3     student3    9         chem 
    4     student4    11        chem 

Teacher2 name
    id    name       class    subject
    1     student1    8         chem 
    2     student2    9         phy 
    3     student3    9         chem 
    4     student4    11        chem 

标签: mysqllaravel

解决方案


我认为那$students是收藏。然后你可以使用groupBy 方法。你可以像这样重写你的代码:

@php
$index = 1;
@endphp

@foreach($students->groupBy('teacher_name') as $teacherName => $subStudents)
<h2>{{$teacherName}}</h2>
<table class="table">
    <thead>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Class</th>
            <th>Subject</th>
        </tr>
    </thead>
    <tbody>
        @foreach($subStudents as $student)
            <tr>
                <td>{{$index }}</td>
                <td>{{$student->name }}</td>
                <td>{{$student->class}} </td>
                <td>{{$student->subject }} </td>
            </tr>
        @php
            $index++;
        @endphp
        @endforeach
    </tbody>
</table>
@endforeach

让我知道这是否回答了您的问题。


推荐阅读