我是Laravel的初学者,我想在老师登录后显示相关的学生记录。我已经实现了登录页面。
这是我的表
Teachers
+----+--------------+
| id | teacher_name |
+----+--------------+
| 1 | John |
+----+--------------+
| 2 | Tommy |
+----+--------------+
Students
+----+--------------+---------------+------------+
| id | student_name | course | teacher_id |
+----+--------------+---------------+------------+
| 1 | Emma | Learn Laravel | 1 |
+----+--------------+---------------+------------+
| 2 | Olivia | Learn Java | 2 |
+----+--------------+---------------+------------+
| 3 | Charlotte | Learn Laravel | 1 |
+----+--------------+---------------+------------+
通常,我会在会话中获得教师ID并在PHP中执行此查询
SELECT * FROM Teachers, Students WHERE students.teacher_id = '$teacher_id';
如何在教师登录后搜索他的学生信息并将其显示在Laravel 5的简单表格中?
答案 0 :(得分:0)
在Student
模型中添加以下关系。
public function teacher ()
{
return $this->belongsTo(Teacher::class);
}
然后在您的查询中
$teacherId = 123; // Set this
$studentWithTeachers = Student::with('teachers')->where('teacher_id', $teacherId);->get();
答案 1 :(得分:0)
正如Gayan在答案中所说,添加与模型的关系应该是你的第一步:
学生模特:
public function teacher ()
{
return $this->belongsTo(Teacher::class);
}
教师模型:
public function students ()
{
return $this->hasMany(Student::class);
}
但与Gayan不同,让老师和学生一起学习更有意义:
$teacher = Teacher::with('students')->findOrFail($teacherID);
您需要将techer变量从控制器传递给您的视图:
return view('example.template', ['teacher', $teacher]);
并在您的刀片模板中显示如下内容:
<table>
@forelse($teacher->students as $student)
<tr>
<td>{{ $student->name }}</td>
</tr>
@empty
<tr>
<td>No Students found</td>
</tr>
@endforelse
</table>