老师有很多学生.当我显示教师列表时,我还想显示每个教师的学生计数.我怎样才能用口才做到这一点呢?
我可以从这里找到老师,
$teacher= Teacher::where('teacher_status','active')->get();
个
我可以从中找出学生人数
$student_count = Student::where('teacher_id','teachers.id')->count();
个
如何组合这两个查询并在单个数组/集合中返回响应?
老师有很多学生.当我显示教师列表时,我还想显示每个教师的学生计数.我怎样才能用口才做到这一点呢?
我可以从这里找到老师,
$teacher= Teacher::where('teacher_status','active')->get();
个
我可以从中找出学生人数
$student_count = Student::where('teacher_id','teachers.id')->count();
个
如何组合这两个查询并在单个数组/集合中返回响应?
In your teacher model, create the relationship students:个
class Teacher extends Model
{
public function students()
{
return $this->hasMany(Student::class, 'teacher_id');
}
}
In your controller you can do the following:个
public function example(){
$teachers = Teacher::where('teacher_status','active')->withCount('students')->get();
return view('teacherViewExample', compact('teachers'));
}
In your view(教师视图示例):
<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
有时,您可能想要计算 给定的关系,而不实际加载模型.要完成 为此,您可以使用with Count方法.With Count方法将 在生成的模型上放置一个{Relation}_Count属性: