Php Laravel中3种模型之间的关系

Php Laravel中3种模型之间的关系,php,laravel,Php,Laravel,我试图在Laravel 5.6中的3个模型之间建立关系 这是我的桌子 部门 身份证 名字 主题 身份证 名字 教师 身份证 名字 教学 身份证教师 身份证科 身份证主题 所有表之间的关系是多对多的 老师可以在许多部门教许多科目 系属于许多学科 这门学科属于许多部门 如何在教师、系和科目模型中建立这些关系?您可以尝试以下方法: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Dep

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

这是我的桌子

部门

  • 身份证
  • 名字
主题

  • 身份证
  • 名字
教师

  • 身份证
  • 名字
教学

  • 身份证教师
  • 身份证科
  • 身份证主题
所有表之间的关系是多对多的

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

  • 系属于许多学科

  • 这门学科属于许多部门


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

您可以尝试以下方法:

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

非常感谢。如何同步所有这些模型?我试过这个$教师=新教师()$教师->姓名=$request->姓名$教师->保存()$教=新教()$教学->教师id=$teacher->id$教学->部门->同步($request->departments,false)$教学->主题->同步($request->主题,false);