model hasManyThrough 使用枢轴模型的关系

问题描述 投票:0回答:2

我有以下模型/表:

branch:
    id - integer

department:
    id - integer

teacher:
    id  - integer
    branch_department_id - integer

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

我想模拟

hasManythrough
branch
s
之间的
teacher

关系

所以从一个特定的

branch
我想让所有老师通过与那个相关的每一个
branch_department
branch

我怎么定义这个?

php laravel eloquent laravel-query-builder eloquent-relationship
2个回答
0
投票

添加 branch_department 模型和:

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

0
投票

如果你还没有定义一个

BranchDepartment
模型。

class BranchDepartment extends Pivot
{
}

从这里你可以在你的

hasManyThrough
模型上定义
Branch
关系。

public function teachers()
{
    return $this->hasManyThrough(Teacher::class, BranchDepartment::class);
}
© www.soinside.com 2019 - 2024. All rights reserved.