首页 文章

Laravel中3种模型的关系

提问于
浏览
2

我试图在Laravel 5.6中 Build 3个模型之间的关系

这是我的表格

departments

  • id

  • 名字

subjects

  • id

  • 名字

teachers

  • id

  • 名字

teach

  • id_teacher

  • id_department

  • id_subject

所有表之间的关系是多对多的 .

  • 老师可以在很多部门教授很多科目

  • 部门属于很多学科

  • 主题属于许多部门

如何在教师,部门和主题模型中 Build 这些关系?

1 回答

  • 2

    你可以尝试这样的事情:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Department extends Model
    {
        /**
         * The teachs that belong to the department.
         */
        public function teachs()
        {
            return $this->belongsToMany('App\Teach', 'teach_department', 'department_id', 'teach_id');
        }
    }
    
    class Subject extends Model
    {
        /**
         * The teachs that belong to the subject.
         */
        public function teachs()
        {
            return $this->belongsToMany('App\Teach', 'teach_subject', 'subject_id', 'teach_id');
        }
    }
    
    class Teacher extends Model
    {
        /**
         * The teachs that belong to the teacher.
         */
        public function teachs()
        {
            return $this->belongsToMany('App\Teach', 'teach_teacher', 'teacher_id', 'teach_id');
        }
    }
    
    class Teach extends Model
    {
        /**
         * The departments that belong to the teach.
         */
        public function departments()
        {
            return $this->belongsToMany('App\Department', 'teach_department', 'teach_id', 'department_id');
        }
    
        /**
         * The subjects that belong to the teach.
         */
        public function subjects()
        {
            return $this->belongsToMany('App\Subject', 'teach_subject', 'teach_id', 'subject_id');
        }
    
        /**
         * The teachers that belong to the teach.
         */
        public function teachers()
        {
            return $this->belongsToMany('App\Teacher', 'teach_teacher', 'teach_id', 'teacher_id');
        }
    }
    

相关问题