laravel模式设计多对多

rdrgkggo  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(301)

你好,我正在尝试建立中学教育的学校管理系统,我有一个erm的设计,我想问拉威尔处理这种类型的关系多对多?如果我做错了,请修改,因为我是初学者,谢谢。。

628mspwn

628mspwn1#

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-对很多人来说

相关问题