简体   繁体   中英

How to query through nested Laravel relationships the eloquent ORM way

I have a relationship that is almost 5 levels deep.

In my blades I use this all time without a problem. For example:

{{ $user->team->department->region->company->name ?? ''}}

How would I go about querying all users that belong to a company?

$users = User::where($user->team->department->region->company->id, '=', 1)->get(); ?????

Company Relationships:

class Company extends Model
{
    public function region() {

        return $this->hasMany('App\Region', 'company_id', 'id');

    }
}

Region Relationships:

class Region extends Model
{
    public function company() {

        return $this->hasOne('App\Company', 'id', 'company_id');

    }
    public function department() {

        return $this->hasMany('App\Department', 'region_id', 'id');

    }
}

Department Relationships:

class Department extends Model
{
    public function region() {

        return $this->hasOne('App\Region', 'id', 'region_id');

    }

    public function team() {

        return $this->hasMany('App\Team', 'department_id', 'id');

    }

}

Team Relationships:

class Team extends Model
{

    public function department() {

        return $this->hasOne('App\Department', 'id', 'department_id');

    }

    public function user() {

        return $this->hasMany('App\User', 'team_id', 'id');

    }

}

User Relationships:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function team() {

        return $this->hasOne('App\Team', 'id', 'team_id');

    }
}

I know there must be some easy way to query through nested relationships that Laravel provides a way for or a some facility for, but I have yet to find any decent examples from Googling around.

You can use this package for your need.

https://github.com/staudenmeir/eloquent-has-many-deep

read the instructions, depth of the relationship is not limited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM