我有以下模型/表:
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
有多个teacher
s
我想在branch
和teacher
之间建立一个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'
);
}
}