1
0
Fork 0
party-rank-server/app/Admin/Services/BaseService.php

152 lines
3.6 KiB
PHP

<?php
namespace App\Admin\Services;
use Illuminate\Database\Eloquent\Model;
use Slowlyo\OwlAdmin\Services\AdminService;
/**
* @method Region getModel()
* @method Region|\Illuminate\Database\Query\Builder query()
*/
class BaseService extends AdminService
{
protected string $modelName = '';
protected array $withRelationships = [];
protected string $modelFilterName = '';
public function getTree()
{
$list = $this->query()->get()->toArray();
return array2tree($list);
}
public function getModelFilter()
{
return $this->modelFilterName;
}
public function listQuery()
{
$model = $this->getModel();
$filter = $this->getModelFilter();
$query = $this->query();
if ($this->withRelationships) {
$query->with($this->withRelationships);
}
if ($filter) {
$query->filter(request()->input(), $filter);
}
return $query->orderByDesc($model->getKeyName());
}
public function list()
{
$query = $this->listQuery();
$list = (clone $query)->paginate(request()->input('perPage', 20));
$items = $list->items();
$total = $list->total();
return compact('items', 'total');
}
public function getDetail($id)
{
return $this->query()->with($this->withRelationships)->find($id);
}
public function store($data): bool
{
$data = $this->resloveData($data);
$validate = $this->validate($data);
if ($validate !== true) {
$this->setError($validate);
return false;
}
$this->modelName::create($data);
return true;
}
public function update($primaryKey, $data): bool
{
$model = $this->query()->whereKey($primaryKey)->firstOrFail();
$data = $this->resloveData($data, $model);
$validate = $this->validate($data, $model);
if ($validate !== true) {
$this->setError($validate);
return false;
}
return $model->update($data);
}
public function delete(string $ids): mixed
{
$id = explode(',', $ids);
$result = $this->preDelete($id);
if ($result !== true) {
$this->setError($result);
return false;
}
return $this->query()->whereIn($this->primaryKey(), $id)->delete();
}
/**
* 处理表单数据
*
* @param array $data
* @param Model $model 空 : 添加, 非空: 修改
* @return array
*/
public function resloveData($data, $model = null)
{
return $data;
}
/**
* 表单验证
*
* @param array $data
* @param Model $model 空: 添加, 非空: 修改
* @return mixed true: 验证通过, string: 错误提示
*/
public function validate($data, $model = null)
{
// $createRules = [
// 'key' => ['required', Rule::unique('keywords', 'key')],
// 'name' => ['required'],
// ];
// $updateRules = [
// 'key' => [Rule::unique('keywords', 'key')->ignore($model->id)]
// ];
// $validator = Validator::make($data, $model ? $updateRules : $createRules, [
// 'key.unique' => ':input 已经存在'
// ]);
// if ($validator->fails()) {
// return $validator->errors()->first();
// }
return true;
}
/**
* 删除的前置方法
*
* @param array $ids 主键id
* @return mixed true: 继续后续操作, string: 中断操作, 返回错误提示
*/
public function preDelete(array $ids)
{
return true;
}
}