答案 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