Laravel Schema design many to many

Grace

hello i'm trying to build school management system on secondary education and i have a ERM design i would Like to ask does laravel handle this type of relationship Many to many? please amend if i'm doing it wrongly since i'm a beginner thanks..

ERMenter image description here

rkj

With 2 db tables many to many reationship

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

Models

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
     }
}

Now Save data

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

Note: similarly you can create relation for other models

For details check https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related