【发布时间】:2018-06-05 06:34:32
【问题描述】:
我正在尝试为大学生构建一个应用程序。
我的想法是从数据库中检索数据,根据学生所在的学期为每个学生显示课程。换句话说,如果学生 A 在第二学期,并且假设课程数据库仅在第二学期举行,那么对于学生 A,我应该在页面上仅将数据库作为符合条件的课程。
我有以下表格:
-用户
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
-学期
public function up()
{
Schema::create('semesters', function (Blueprint $table) {
$table->increments('id');
$table->integer('number');
$table->timestamps();
});
}
additional_info_students
public function up()
{
Schema::create('additional_info_students', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('first_name', 255);
$table->string('last_name', 255);
$table->integer('faculty_number')->unique();
$table->integer('group_number');
$table->integer('year');
$table->integer('semester_id')->unsigned();
$table->foreign('semester_id')->references('id')->on('semesters');
$table->timestamps();
});
}
-课程
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('language', 10);
$table->longText('description', 30000000);
$table->integer('semester_id')->unsigned();
$table->foreign('semester_id')->references('id')->on('semesters');
$table->timestamps();
});
}
-courses_assign_students
public function up()
{
Schema::create('courses_assign_students', function (Blueprint $table) {
$table->increments('id');
$table->integer('student_id')->unsigned();
$table->foreign('student_id')->references('user_id')->on('additional_info_students');
$table->integer('courses_id')->unsigned();
$table->foreign('courses_id')->references('id')->on('courses');
$table->timestamps();
});
}
这行得通吗?我似乎无法正确加入他们以获得我需要的东西。
此外,当我加入表并尝试从集合中打印一个属性(如 student_id)时,我收到一个错误未定义属性。
public function showAll() {
$courses = CoursesAssignStudents::join('courses', 'courses_assign_students.courses_id', '=', 'courses.id')
->join('additional_info_students', 'courses_assign_students.student_id', '=', 'additional_info_students.user_id')
->select('courses.*','additional_info_students.user_id as student_id', 'first_name', 'last_name', 'faculty_number','group_number','year','additional_info_students.semester_id as sem_id')->get();
return view('courses', compact('courses'));
}
此外,通过在视图中传递数据,我正在循环浏览课程,并且我两次获得相同的课程,而我应该获得一次。
最后,我使用的是 Laravel 5.4
非常感谢您的帮助!
提前谢谢:)
【问题讨论】:
-
您需要在模型中设置关系。请参阅documentation。
-
嗨,您的模型关系是如何设置的?另请注意,为了在多对多之间访问表中的数据,您必须使用数据透视表,例如:$courses->pivot->student_id,除此之外,您不能更精确地做什么?跨度>
-
嗨 GaimZz,我没有在模型中设置关系。我正在尝试将数据传递给视图。我想根据学期为每个学生显示正确的课程。因此,如果学生是第二学期并且 DB 和数学课程在第二学期,我想要 DB 和数学。目前课程显示两次。 DB 数据库数学 数学。希望这是有道理的
-
你能在你的视图文件中展示你的循环吗?
-
这就是我的做法:@foreach($courses as $course) @endforeach