php 使用透视模型的模型hasManyThrough关系

yi0zb3m4  于 2023-04-10  发布在  PHP
关注(0)|答案(2)|浏览(154)

我有以下模型/表:

branch:
    id - integer

department:
    id - integer

teacher:
    id  - integer
    branch_department_id - integer

branch_department:
    id - integer
    branch_id - integer
    department_id - integer
  • 通过数据透视表branch_department,每个branch具有多个departments
  • 每个branch_department有许多teacher

我想在branchteacher之间建立一个hasManythrough关系模型
因此,从特定的branch开始,我想让所有教师通过与该branch相关的每个branch_department
我该如何定义这一点?

ubby3x7f

ubby3x7f1#

添加分支_department模型并:

class Branch extends Model
{
    public function teachers()
    {
        return $this->hasManyThrough(
            Teacher::class,
            BranchDepartment::class,
            'branch_id',
            'id',
            'id',
            'teacher_id'
        );
    }
}
xurqigkl

xurqigkl2#

如果您还没有定义BranchDepartment模型。

class BranchDepartment extends Pivot
{
}

在这里,您可以在Branch模型上定义hasManyThrough关系。

public function teachers()
{
    return $this->hasManyThrough(Teacher::class, BranchDepartment::class);
}

相关问题