簡體   English   中英

如何通過 Eloquent 獲取單個集合中每位教師的學生數

[英]How to get the counts of Student for each Teachers in a single collection by Eloquent

一個老師有很多學生。 當我顯示教師列表時,我還想顯示每位教師的學生人數。 我如何使用 Eloquent 來做到這一點?

我可以從這里找到教師, $teacher= Teacher::where('teacher_status','active')->get();

我可以從這個$student_count = Student::where('teacher_id','teachers.id')->count();中找到學生人數

我如何結合這兩個查詢並在單個數組/集合中返回響應?

如果你想計算與教師相關的學生人數而不實際加載他們,你可以使用 withCount 方法,這會在你的結果模型上添加一個由 {relation}_count 列命名的新屬性。 例如:

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

你還需要和你的老師 model hasMany relation method to Students

在你的老師 model 中,創建學生關系:

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

在您的 controller 中,您可以執行以下操作:

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>Students Count</th>
    </tr>
  </thead>
  <tbody>
    @foreach($teachers as $teacher)
    <tr>
      <td>{{ $teacher->name }}</td>
      <td>{{ $teacher->students_count }}</td>
    </tr>
    @endforeach
  </tbody>
</table>

有關如何在此處使用withCount()的完整文檔: https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models

有時您可能想要計算給定關系的相關模型的數量,而無需實際加載模型。 為此,您可以使用 withCount 方法。 withCount 方法將在生成的模型上放置一個 {relation}_count 屬性:

如果前后端分離,即后端為Laravel,前端為Angular,下面以Laravel為例:

在 api.php,

Route::get('teacher-with-students-count', 'TeacherController@getTeacherWithStudentsCount');
 

在老師.php(模型)

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

在 TeacherController.php

public function getTeacherWithStudentsCount()
    {
        $teachers = Teacher::where('teacher_status','active')->withCount('students')->get();

        return $this->giveSuccessResponse($teachers);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM