使用Eloquent构建跨越四个或更多表的关系

时间:2014-01-31 23:14:17

标签: orm laravel-4 relationship eloquent

这是一个架构:

users: id

schools: id | district_id

school_users: id | school_id | user_id

districts: id

如何在Eloquent中建立关系以返回$ district->用户?

class District
{
    public function users()
    {
        //something that mirrors this functionality
        return $this->hasManyThroughThrough("User","SchoolUser","School");
    }
}

1 个答案:

答案 0 :(得分:0)

你应该跨越两种关系:

class District
{
    public function users()
    {
        return $this->hasMany('School');
    }
}

class School
{
    public function users()
    {
        return $this->belongsToMany('User');
    }
}

class User
{
}

$books = District::with('schools.users')->get();