使用pivot模型建模hasManyThrough关系



我有以下模型/表:

branch:
id - integer
department:
id - integer
teacher:
id  - integer
branch_department_id - integer
branch_department:
id - integer
branch_id - integer
department_id - integer
  • 每个branch通过透视表branch_department有多个departments
  • 每个branch_department有多个teachers

我想在branchteacher之间建立一个hasManythrough关系模型

所以从一个特定的branch开始,我想让所有的老师通过与branch相关的每个branch_department

我如何定义这个?

如果您还没有定义BranchDepartment模型

class BranchDepartment extends Pivot
{
}

从这里你可以在你的Branch模型上定义hasManyThrough关系。

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

add branch_department model and:

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

相关内容

  • 没有找到相关文章

最新更新