80 lines
2.2 KiB
PHP
80 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Services;
|
|
|
|
use App\ModelFilters\KeywordFilter;
|
|
use App\Models\Keyword;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\Rule;
|
|
|
|
/**
|
|
* @method Keyword getModel()
|
|
* @method Keyword|\Illuminate\Database\Query\Builder query()
|
|
*/
|
|
class KeywordService extends BaseService
|
|
{
|
|
protected array $withRelationships = [];
|
|
|
|
protected string $modelName = Keyword::class;
|
|
|
|
protected string $modelFilterName = KeywordFilter::class;
|
|
|
|
public function getTree($filters = [])
|
|
{
|
|
$list = $this->query()->filter($filters, $this->getModelFilter())->sort()->get();
|
|
|
|
return array2tree($list->toArray(), $list->min('parent_id') ?: 0);
|
|
}
|
|
|
|
public function list()
|
|
{
|
|
return ['items' => $this->getTree(request()->all())];
|
|
}
|
|
|
|
public function delete(string $ids): mixed
|
|
{
|
|
$ids = explode(',', $ids);
|
|
if (count($ids) == 1) {
|
|
$this->query()->where('path', 'like', '%-'.$ids[0].'-%')->delete();
|
|
}
|
|
|
|
return $this->query()->whereIn('id', $ids)->delete();
|
|
}
|
|
|
|
public function validate($data, $id = null)
|
|
{
|
|
$createRules = [
|
|
'key' => ['required', Rule::unique('keywords', 'key')],
|
|
'name' => ['required'],
|
|
];
|
|
$updateRules = [
|
|
'key' => [Rule::unique('keywords', 'key')->ignore($id)]
|
|
];
|
|
$validator = Validator::make($data, $id ? $updateRules : $createRules, [
|
|
'key.unique' => ':input 已经存在'
|
|
]);
|
|
if ($validator->fails()) {
|
|
return $validator->errors()->first();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public function resloveData($data)
|
|
{
|
|
$parent_id = data_get($data, 'parent_id');
|
|
if (!is_null($parent_id)) {
|
|
if ($parent_id) {
|
|
$parent = Keyword::findOrFail($parent_id);
|
|
$data['level'] = $parent->level + 1;
|
|
$data['type_key'] = $parent->key;
|
|
$data['path'] = $parent->path.$parent_id.'-';
|
|
} else {
|
|
$data['level'] = 1;
|
|
$data['path'] = '-';
|
|
$data['parent_id'] = 0;
|
|
}
|
|
}
|
|
return $data;
|
|
}
|
|
}
|