Laravel Schema设计多对多

时间:2018-06-28 03:09:07

标签: php mysql database laravel oop

您好,我正在尝试在中学教育上构建学校管理系统,我有一个ERM设计,我想问laravel是否处理这种类型的关系?很多对很多?,如果我我做错了,因为我是初学者,所以做错了。

ERM enter image description here

1 个答案:

答案 0 :(得分:1)

  

具有2个db表,多对多关系

students(id,name,created_at,updated_at)
subjects(id, name, created_at,updated_at)
student_subjects(id, student_id, subject_id)
  

模型

class Student extends Model{
     public function subjects(){
         return $this->belongsToMany(Subject::class, 'student_subjects'); //here student_subjects is as a pivot table
     }
}

class Subject extends Model{
     public function stdents(){
         return $this->belongsToMany(Student::class, 'student_subjects'); //here student_subjects is as a pivot table
     }
}
  

现在保存数据

$student = Student::find(1);
$student->subjects()->attach(2); // it will save subject 2 for student 1 in `student_subjects` table.

注意:类似地,您可以为其他模型创建关系

有关详细信息,请检查https://laravel.com/docs/5.6/eloquent-relationships#many-to-many