Search code examples
laravellaravel-relations

How to use Laravel's hasManyThrough on self-referenced tables


I have the User and Regional models, which I want to get some regionals from the user type of supervisor. So here is how I define the relationship.

public function regional()
{
    return $this->belongsTo(Regional::class);
}

/**
 * Get all user that belongs to this supervisor
 *
 * @return mixed
 */
public function amOfSupervisor()
{
    return $this->hasMany(User::class, 'supervisor_id');
}

I can get the user's regional by $user->regional, but how to get all regional based on the user that belongs to this user? I've tried hasManyThrough() but always an error. What's wrong, or what should I do?

public function RegionalSV()
{
    return $this->hasManyThrough(Regional::class, 
        User::class,'supervisor_id', 'regional_id');
}

Solution

  • hasManyThrough uses when Project has Environment and Environment has departement we can use

    hasManyThrough( departement::class,Environment::class,'project_id','Environment_id','id','id') 
    

    so you have User has many users and each user belongs to regional

    you can do

     Regional::whereExists(function($query){
    $query->selectRaw('1')->from('users')->whereColumn('users.regional_id','regionals.id')
    ->where('users.supervisor_id',$this->id);
    })->get()
    

    or

    Regional::join(self::class,'users.regional_id','=','regionals.id')
    ->where('users.supervisor_id',$this->id)->get();