[英]Many to many eloquent query Laravel
我有一个学生表、一个课程表和一个 student_courses pivot 表。
我的模型如下:
{
public $timestamps= false;
public function courses()
{
return $this->belongsToMany(Course::class);
}
}
class Course extends Model
{
public $timestamps= false;
public function students()
{
return $this->belongsToMany(Student::class);
}
}
我的表如下所示:
Schema::create('courses', function (Blueprint $table) {
$table->increments('id');
$table->String('code');
$table->String('name');
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('first');
$table->string('last');
Schema::create('course_student', function (Blueprint $table) {
$table->increments('id');
$table->integer('course_id')->unsigned();
$table->foreign('course_id')->references('id')->on('courses');
$table->integer('student_id')->unsigned();
$table->foreign('student_id')->references('id')->on('students');
我已经成功地添加了学生和课程,并将学生附加到课程中,所以我知道我的模型正在工作。
我想在我的 controller 中创建一个可以在视图中访问的查询 function。 我想要一个查询,它给我一个每个学生的列表以及他们所学的课程。
例如
学生1课程1
学生1课程2
学生 2 课程 1
如何使用 foreach 将数据输入到表中来进行查询以在我的视图中使用? 我已经成功输出了所有学生姓名和课程名称,但是我不明白如何查询pivot表
当您定义关系时,您不必手动查询 pivot 表。
我会在 controller 中做类似的事情:
$students = Student::with('courses')->get();
据我了解,您想将数据放入表中,这是一个两列示例:
<table>
<thead>
<tr>
<th>Name</th>
<th>Courses</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{ $student->first}} {{ $student->last}}</td>
<td>
@foreach($student->courses as $course)
{{ $course->name }},
@endforeach
</td>
</tr>
@endforeach
<tbody>
</table>
你会得到这个表:
| Student Name | Courses |
|:-------------|-----------:|
| John | C1, C2, C3 |
| Marc | CA, CB, CC |
在你身上 controller:
$students = Student::with('courses')->get();
在视图内部:
@foreach($students as $student)
@foreach($student->courses as $course )
{{ $student->first . $student->last }} {{ $course->name }}
@endforeach
@endforeach
获取有课程的学生数据
$students = Student::with('courses')->get();
在视野中
@foreach($students as $student)
{{ $student->first }} {{ $student->last }} // to display student name
@foreach($student->courses as $course) // loop of courses of student
{{ $course->name }} // to display student name
@endforeach
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.