Laravel多对多关系课程和教师

时间:2018-02-22 23:45:56

标签: laravel eloquent

我的应用程序(用Laravel编写)有类别教师课程模型。

课程可以进入一个类别,一个类别可以包含多个课程......

class Course extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

class Category extends Model
{
    public function courses()
    {
        return $this->hasMany('App\Course');
    }
}
class Teacher extends Model
{

}

我目前的问题是我需要建立一个关系,教师可以在其下面有多个课程,而课程可以有多个教师。这就是我混淆的地方。

我目前的数据库表结构:

Schema::create('courses', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('course_id');
            $table->integer('category_id');
            $table->string('name');
            // Teachers? **shrug**
            $table->timestamps();
        });

Schema::create('teachers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('teacher_id');
            $table->integer('name');
            $table->timestamps();
        });
Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id');
            $table->string('name');
            $table->timestamps();
        });

1 个答案:

答案 0 :(得分:3)

coursesteachers制作many to many relationship

因此,您应该在many-to-manyTeacher模型中定义Course关系:

  

应用\ Teacher.php

/**
 * The Teacher has many Courses.
 */
public function courses()
{
    return $this->belongsToMany('App\Course');
}
  

应用\ Course.php

/**
 * The Course has many Teachers.
 */
public function teachers()
{
    return $this->belongsToMany('App\Teacher');
}

此方法将查找名为course_teacher的表。 course_teacher表来自相关模型名称的字母顺序,包含course_idteacher_id列。

如果要覆盖表的名称,只需将其作为documentation状态的关系中的参数传递。

所以现在你需要在你的数据库中拥有该表:

Schema::create('courses', function (Blueprint $table) {
            $table->increments('course_id');
            $table->unsignedInteger('category_id');
            $table->string('name');
            $table->timestamps();
        });

Schema::create('teachers', function (Blueprint $table) {
            $table->increments('teacher_id');
            $table->integer('name');
            $table->timestamps();
        });
Schema::create('categories', function (Blueprint $table) {
            $table->increments('category_id');
            $table->string('name');
            $table->timestamps();
        });

// This is the missing table

Schema::create('course_teacher', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('course_id');
            $table->unsignedInteger('teacher_id');
        });

旁注

我注意到你的表中有两列(我假设)可能相等:identity_id,所以如果你想/需要自定义{{1模型匹配你的一个表,只需在模型类中重写它:

  

应用\ Course.php

Primary key

您还可以配置其他参数,例如表名。阅读文档的Model conventions部分。