【发布时间】:2020-03-11 15:06:18
【问题描述】:
我有一个学生表、一个课程表和一个 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');
我已成功添加学生和课程,并将学生附加到课程,因此我知道我的模型正在运行。
我想在我的控制器中创建一个可以在视图中访问的查询函数。我想要一个查询,它可以为我提供每个学生的列表以及他们所在的课程。
例如
学生1课程1
学生1课程2
学生 2 课程 1
如何使用 foreach 将数据输入到表中来进行查询以在我的视图中使用?我已经成功输出了所有学生姓名和课程名称,但是我不明白如何查询数据透视表
【问题讨论】:
-
你能出示你的代码吗