【问题标题】:How to get the counts of Student for each Teachers in a single collection by Eloquent如何通过 Eloquent 获取单个集合中每位教师的学生人数
【发布时间】:2023-01-28 01:48:51
【问题描述】:

一个老师有很多学生。当我显示教师列表时,我还想显示每位教师的学生人数。我如何使用 Eloquent 来做到这一点?

我可以从这里找到老师, $teacher= Teacher::where('teacher_status','active')->get();

我可以从中找到学生人数 $student_count = Student::where('teacher_id','teachers.id')->count();

我如何结合这两个查询并在单个数组/集合中返回响应?

【问题讨论】:

    标签: laravel eloquent subquery


    【解决方案1】:

    如果你想计算与教师相关的学生人数而不实际加载他们,你可以使用 withCount 方法,这会在你的结果模型上添加一个由 {relation}_count 列命名的新属性。例如:

    Teacher::where('teacher_status','active')->withCount('students')->get();
    

    您还需要和您的 Teacher 模型有许多与 Students 的关系方法

    【讨论】:

      【解决方案2】:

      在您的教师模型中,创建学生关系:

      class Teacher extends Model
      {
          public function students()
          {
              return $this->hasMany(Student::class, 'teacher_id');
          }
      }
      

      在您的控制器中,您可以执行以下操作:

      public function example(){
          $teachers = Teacher::where('teacher_status','active')->withCount('students')->get();
          
          return view('teacherViewExample', compact('teachers'));
      }
      

      在你看来(teacherViewExample):

      <table>
        <thead>
          <tr>
            <th>Teacher Name</th>
            <th>Number of Students</th>
          </tr>
        </thead>
        <tbody>
          @foreach ($teachers as $teacher)
          <tr>
            <td>{{ $teacher->name }}</td>
            <td>{{ $teacher->students->count() }}</td>
          </tr>
          @endforeach
        </tbody>
      </table>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-22
        • 2011-12-15
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-04
        相关资源
        最近更新 更多