Reputation: 299
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..
Upvotes: 1
Views: 311
Reputation: 8297
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
Upvotes: 1