Files
hyperf_data/app/JsonRpc/Service/CampusService.php
2025-09-18 15:54:38 +08:00

84 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\JsonRpc\Service;
use App\JsonRpc\Contract\CampusServiceInterface;
use App\Model\Campus;
use Hyperf\RpcServer\Annotation\RpcService;
use RuntimeException;
#[RpcService(
name: 'DataCampus',
server: 'jsonrpc-http',
protocol: 'jsonrpc-http',
publishTo: 'nacos'
)]
class CampusService implements CampusServiceInterface
{
public function getCampus(int $id): array
{
$campus = Campus::find($id);
if (! $campus) {
throw new RuntimeException("校区不存在: {$id}");
}
return $campus->toArray();
}
public function batchGetCampus(array $ids): array
{
if (empty($ids)) {
return [];
}
$campuses = Campus::whereIn('id', $ids)->get()->toArray();
return array_column($campuses, null, 'id');
}
public function getCampusByProvince(string $province): array
{
return Campus::province($province)
->level(3)
->get()
->toArray();
}
public function getCampusByCity(string $province, string $city): array
{
return Campus::province($province)
->city($city)
->level(3)
->get()
->toArray();
}
public function getCampusHierarchy(int $campusId): array
{
$hierarchy = [];
$current = Campus::find($campusId);
if (! $current) {
return $hierarchy;
}
// 从校区向上追溯层级
while ($current) {
array_unshift($hierarchy, [
'id' => $current->id,
'name' => $current->name,
'level' => $current->level,
'province' => $current->province,
'city' => $current->city,
]);
if ($current->parent_id === 0) {
break;
}
$current = Campus::find($current->parent_id);
}
return $hierarchy;
}
}