【问题标题】:Relationship between 3 Models in LaravelLaravel中3个模型之间的关系
【发布时间】:2018-10-17 00:56:55
【问题描述】:

我正在尝试在 Laravel 5.6 中建立 3 个模型之间的关系

这是我的桌子

部门

  • 身份证
  • 姓名

主题

  • 身份证
  • 姓名

教师

  • 身份证
  • 姓名

  • id_teacher
  • id_department
  • id_subject

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

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

  • 科属多学科

  • 主题属于多个部门

如何在教师、部门和学科模型中建立这些关系?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你可以试试这样的:

    <?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');
        }
    }
    

    【讨论】:

    • 非常感谢。如何同步所有这些模型?我试过这个。 $老师=新老师(); $teacher->name = $request->name; $老师->保存(); $teach = 新教(); $teach->teacher_id = $teacher->id; $teach->departments->sync($request->departments, false); $teach->subjects->sync($request->subjects, false);
    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 2019-10-06
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多