老师有很多学生.当我显示教师列表时,我还想显示每个教师的学生计数.我怎样才能用口才做到这一点呢?

我可以从这里找到老师, $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属性:

Laravel相关问答推荐

当两个外键都在同一个表上时创建直通关系

Laravel:如何强制使用 HTTPS?

Carbon现在时间错了

如何在 Laravel 4 中使用没有 id 的 Eloquent 更新数据

Laravel 5.6 - 如何在 api 控制器中获取 auth()->user() 或 $response->user()?

Laravel 5.1 是否与 PHP 7 兼容

Laravel Request::input 调用未定义的方法

Laravel 4 定义 RESTful 控制器

使用限制排队 Guzzle 请求

如何仅从 laravel FormRequest 中获取经过验证的数据?

在 Laravel 5.4 中将中间件应用于除 `setup/*` 之外的所有路由

laravel 4 - 如何限制(采取和跳过)Eloquent的 ORM?

控制器外部的 Laravel 访问请求对象

在Lumen框架中启用会话

Laravel 无法创建根目录

如何处理 php (Laravel api) 和 javascript (AngularJS) 之间的日期时间

将 Laravel 集合排序为 ID 数组

如何在 laravel 用户删除中重置自动增量?

Laravel 5.4 - Mix - 如何运行浏览器实时重新加载

Laravel 在域和子域中共享 cookie 检测问题