我有用户和区域模型,我想从用户类型的主管那里获得一些区域。以下是我如何定义这种关系。
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');
}
我可以通过$user->regional
获取用户的区域,但如何基于属于该用户的用户获取所有区域?我试过hasManyThrough()
,但总是出错。怎么了,或者我该怎么办?
public function RegionalSV()
{
return $this->hasManyThrough(Regional::class,
User::class,'supervisor_id', 'regional_id');
}
hasManyThrough在Project有Environment和Environment有department时使用我们可以使用
hasManyThrough( departement::class,Environment::class,'project_id','Environment_id','id','id')
所以你有User有很多用户,每个用户都属于区域
你可以做
Regional::whereExists(function($query){
$query->selectRaw('1')->from('users')->whereColumn('users.regional_id','regionals.id')
->where('users.supervisor_id',$this->id);
})->get()
或
Regional::join(self::class,'users.regional_id','=','regionals.id')
->where('users.supervisor_id',$this->id)->get();