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.
Comments