70 lines
2.1 KiB
PHP
70 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Admin;
|
|
|
|
use App\Models\{ArticleCategory, Article};
|
|
use Illuminate\Http\Request;
|
|
use App\Filters\ArticleCategoryFilter;
|
|
|
|
/**
|
|
* @method ArticleCategory getModel()
|
|
* @method ArticleCategory|\Illuminate\Database\Query\Builder query()
|
|
*/
|
|
class ArticleCategoryService extends BaseService
|
|
{
|
|
protected string $modelName = ArticleCategory::class;
|
|
protected string $modelFilterName = ArticleCategoryFilter::class;
|
|
|
|
public function getTree()
|
|
{
|
|
$list = $this->query()->filter(request()->all(), $this->modelFilterName)->sort()->get()->toArray();
|
|
return array2tree($list, request('parent_path', 0));
|
|
}
|
|
|
|
public function list()
|
|
{
|
|
return ['items' => $this->getTree()];
|
|
}
|
|
|
|
public function store($data): bool
|
|
{
|
|
$pid = data_get($data, 'parent_id');
|
|
if ($pid && $parent = ArticleCategory::find($pid)) {
|
|
$data['level'] = $parent->level + 1;
|
|
$data['path'] = $parent->path . $parent->id . '-';
|
|
} else {
|
|
$data['level'] = 1;
|
|
$data['path'] = '-';
|
|
}
|
|
return parent::store($data);
|
|
}
|
|
|
|
public function update($primaryKey, $data): bool
|
|
{
|
|
$pid = data_get($data, 'parent_id', 0);
|
|
if ($pid && $parent = ArticleCategory::find($pid)) {
|
|
$data['level'] = $parent->level + 1;
|
|
$data['path'] = $parent->path . $parent->id . '-';
|
|
} else {
|
|
$data['level'] = 1;
|
|
$data['path'] = '-';
|
|
}
|
|
return parent::update($primaryKey, $data);
|
|
}
|
|
|
|
public function delete(string $ids): mixed
|
|
{
|
|
$id = collect(explode(',', $ids));
|
|
// 所有下级ID
|
|
foreach ($id as $value) {
|
|
$item_ids = ArticleCategory::where('path', 'like', '%-'.$value.'-%')->pluck('id');
|
|
$id = $id->merge($item_ids);
|
|
}
|
|
$id = $id->unique();
|
|
if (Article::whereIn('category_id', $id)->exists()) {
|
|
return $this->setError('请先删除分类下的文章');
|
|
}
|
|
return $this->query()->whereIn($this->primaryKey(), $id)->delete();
|
|
}
|
|
}
|