belongsTo(Company::class); } public function parent(): BelongsTo { return $this->belongsTo(self::class, 'parent_id'); } public function children(): HasMany { return $this->hasMany(self::class, 'parent_id'); } public function members(): HasMany { return $this->hasMany(CompanyMember::class); } public function management(): HasMany { return $this->members()->whereIn('rank', [CompanyMemberRank::VICE, CompanyMemberRank::CHIEF]); } public function vices(): HasMany { return $this->members()->where(['rank' => CompanyMemberRank::VICE]); } public function employees(): HasMany { return $this->members()->where(['rank' => CompanyMemberRank::EMPLOYEE]); } public function getChiefAttribute() { return $this->members()->where(['rank' => CompanyMemberRank::CHIEF])->first(); } public function addChildren($name, $title): ?Department { $result = null; if (($name = trim($name)) && ($title = trim($title))) { $result = $this->company->departments()->firstOrCreate(['name' => $name]); $result->update(['title' => $title, 'parent_id' => $this->id, 'level' => ++$this->level]); } return $result; } public function addMember(User $user, $position = null): Model { return $this->members()->firstOrCreate(['company_id' => $this->company_id, 'user_id' => $user->id, 'position' => $position]); } public function isMember(CompanyMember $member): bool { return $this->members()->where(['id' => $member->id])->exists(); } public function isParentFor(Department $department): bool { while ($parent = $department->parent) { if ($parent->id === $this->id) return true; $department = $department->parent; } return false; } }