我有用户表,可以将每个用户分配给经理。我有3种类型的经理(国家经理,区域经理和车队经理)。一个区域经理可以拥有许多车队经理和国家经理,一个国家经理可以拥有许多车队经理。我的users表中包含fleet_manager_id,country_manager_id,area_manager_id列,用于引用用户表的id。问题是我不知道如何在同一个表上设置多态关系。移民:
Schema::table('users', function (Blueprint $table) {
$table->integer('fleet_manager_id')->unsigned()->nullable();
$table->foreign('fleet_manager_id')->references('id')->on('users');
$table->integer('country_manager_id')->unsigned()->nullable();
$table->foreign('country_manager_id')->references('id')->on('users');
$table->integer('area_manager_id')->unsigned()->nullable();
$table->foreign('area_manager_id')->references('id')->on('users');
});
我的用户模型:
public function fleetManagers()
{
return $this->hasMany(User::class, 'fleet_manager_id');
}
public function countryManager()
{
return $this->belongsTo(User::class, 'country_manager_id');
}
public function areaManager()
{
return $this->belongsTo(User::class, 'area_manager_id');
}
所以,这是我到目前为止的解决方案:
public function managedByArea()
{
return $this->hasMany(User::class, 'area_manager_id');
}
public function area_manager()
{
return $this->belongsTo(User::class, 'area_manager_id');
}
public function managedByCountry()
{
return $this->hasMany(User::class, 'country_manager_id');
}
public function country_manager()
{
return $this->belongsTo(User::class, 'country_manager_id');
}
public function managedByFleet()
{
return $this->hasMany(User::class, 'fleet_manager_id');
}
public function fleet_manager()
{
return $this->belongsTo(User::class, 'fleet_manager_id');
}