123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- <?php
- namespace App\Services;
- use App\Models\Project;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Slowlyo\OwlAdmin\Services\AdminService;
- /**
- * 项目服务
- *
- * @method Project getModel()
- * @method Project|\Illuminate\Database\Query\Builder query()
- */
- class ProjectService extends AdminService
- {
- protected string $modelName = Project::class;
- /**
- * 获取项目列表
- */
- public function getProjects(int $page, int $perPage, ?string $keyword = null): array
- {
- try {
- $query = $this->query();
- // 如果有关键词,添加搜索条件
- if ($keyword) {
- $query->where(function ($q) use ($keyword) {
- $q->where('title', 'like', "%{$keyword}%")
- ->orWhere('subtitle', 'like', "%{$keyword}%");
- });
- }
- $total = $query->count();
- $items = $query->forPage($page, $perPage)
- ->orderBy('id', 'desc')
- ->get();
- return [
- 'items' => $items,
- 'total' => $total,
- ];
- } catch (\Exception $e) {
- Log::error('获取项目列表失败', [
- 'error' => $e->getMessage(),
- 'params' => func_get_args(),
- ]);
- throw $e;
- }
- }
- /**
- * 创建项目
- *
- * @return mixed
- */
- public function createProject(array $data)
- {
- try {
- return DB::transaction(function () use ($data) {
- // 创建项目记录
- return $this->query()->create($data);
- });
- } catch (\Exception $e) {
- Log::error('创建项目失败', [
- 'error' => $e->getMessage(),
- 'data' => $data,
- ]);
- throw $e;
- }
- }
- /**
- * 更新项目
- *
- * @return mixed
- */
- public function updateProject(int $id, array $data)
- {
- try {
- return DB::transaction(function () use ($id, $data) {
- $project = $this->query()->findOrFail($id);
- // 更新项目信息
- $project->update($data);
- return $project;
- });
- } catch (\Exception $e) {
- Log::error('更新项目失败', [
- 'error' => $e->getMessage(),
- 'id' => $id,
- 'data' => $data,
- ]);
- throw $e;
- }
- }
- /**
- * 删除项目
- */
- public function deleteProject(int $id): bool
- {
- try {
- return DB::transaction(function () use ($id) {
- $project = $this->query()->findOrFail($id);
- // 删除项目
- return $project->delete();
- });
- } catch (\Exception $e) {
- Log::error('删除项目失败', [
- 'error' => $e->getMessage(),
- 'id' => $id,
- ]);
- throw $e;
- }
- }
- /**
- * 获取项目详情
- *
- * @return mixed
- */
- public function getProject(int $id)
- {
- try {
- return $this->query()->findOrFail($id);
- } catch (\Exception $e) {
- Log::error('获取项目详情失败', [
- 'error' => $e->getMessage(),
- 'id' => $id,
- ]);
- throw $e;
- }
- }
- }
|