多对多雄辩的查询Laravel

时间:2019-11-15 12:48:42

标签: php laravel

我有一个学生表,一个课程表和一个student_courses数据透视表。

我的模型如下:

{
    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');

我已经成功添加了学生和课程,并将学生加入课程,所以我知道我的模型正在运行。

我想在控制器中创建一个查询函数,可以在视图中访问它。我想查询一个能给我每个学生以及他们所学课程的列表。

例如

  

Student1课程1

     

Student1课程2

     

Student2课程1

如何使用foreach将数据输入到表中以使查询在视图中使用?我已经成功输出了所有学生的姓名和课程名称,但是我不知道如何查询数据透视表

3 个答案:

答案 0 :(得分:1)

定义关系后,不必手动查询数据透视表。

我会在控制器中做类似的事情:

FIELDS TERMINATED BY ' '
COLLECTION ITEMS TERMINATED BY '\u0002'
MAP KEYS TERMINATED BY '\u0003'

据我了解,您希望将数据放在表中,这是一个两列的示例:

$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>

答案 1 :(得分:1)

在您的控制器上:

$students = Student::with('courses')->get();

并在视图内:

@foreach($students as $student)
    @foreach($student->courses as $course )
       {{ $student->first . $student->last }} {{ $course->name }}
    @endforeach
@endforeach

答案 2 :(得分:1)

获取课程学生的数据

$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