Laravel 模型关联 hasManyThrough 反向关联怎么配置
现在有 3 个数据表
schools:
id
name
grades:
id
name
school_id
students:
id
name
grade_id
我在 School 模型定义了一个远程一对多的关系获取学校的学生
public function students()
{
return $this->hasManyThrough(
Student::class,
Grade::class,
'school_id',
'grade_id',
'id',
'id'
);
}
现在有个需求想在 Student 直接获取 School,
通过在 Student belongsTo(Grade::class)
在 Grade belongsTo(School::class)
这样 $student->grade->school
获取没有问题
我现在想直接 $student->school
有什么优雅的办法
是否类似这样去获取?
public fuction school()
{
return $this->grade()->school();
}
推荐文章: