126 lines
3.1 KiB
PHP
126 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Admin;
|
|
|
|
use Illuminate\Support\Arr;
|
|
use App\Models\ProductCategory;
|
|
use App\Models\Filters\ProductCategoryFilter;
|
|
use App\Traits\UploadTrait;
|
|
|
|
/**
|
|
* @method ProductCategory getModel()
|
|
* @method ProductCategory|\Illuminate\Database\Query\Builder query()
|
|
*/
|
|
class ProductCategoryService extends BaseService
|
|
{
|
|
protected string $modelName = ProductCategory::class;
|
|
protected string $modelFilterName = ProductCategoryFilter::class;
|
|
|
|
use UploadTrait;
|
|
|
|
public function getTree()
|
|
{
|
|
$list = $this->query()->filter(request()->all(), $this->modelFilterName)->orderByDesc('sort')->get();
|
|
$minNum = $list->min('parent_id');
|
|
return !$list->isEmpty() ? array2tree($list->toArray(), $minNum) :[];
|
|
}
|
|
|
|
public function parentIsChild($id, $pid): bool
|
|
{
|
|
$parent = $this->query()->find($pid);
|
|
|
|
do {
|
|
if ($parent->parent_id == $id) {
|
|
return true;
|
|
}
|
|
// 如果没有parent 则为顶级 退出循环
|
|
$parent = $parent->parent;
|
|
} while ($parent);
|
|
|
|
return false;
|
|
}
|
|
|
|
public function list()
|
|
{
|
|
return ['items' => $this->getTree()];
|
|
}
|
|
|
|
public function store($data): bool
|
|
{
|
|
if ($this->hasRepeated($data)) {
|
|
return false;
|
|
}
|
|
|
|
$columns = $this->getTableColumns();
|
|
|
|
$model = $this->getModel();
|
|
|
|
$data['cover'] = $this->saveImage('cover', 'product_category/cover')[0] ?? '';
|
|
foreach ($data as $k => $v) {
|
|
if (!in_array($k, $columns)) {
|
|
continue;
|
|
}
|
|
|
|
$model->setAttribute($k, $v);
|
|
}
|
|
|
|
return $model->save();
|
|
}
|
|
|
|
public function update($primaryKey, $data): bool
|
|
{
|
|
if ($this->hasRepeated($data, $primaryKey)) {
|
|
return false;
|
|
}
|
|
|
|
$columns = $this->getTableColumns();
|
|
|
|
$pid = Arr::get($data, 'parent_id');
|
|
if ($pid != 0) {
|
|
if ($this->parentIsChild($primaryKey, $pid)) {
|
|
$this->setError('父级不允许设置为当前子级');
|
|
return false;
|
|
}
|
|
}
|
|
|
|
$model = $this->query()->whereKey($primaryKey)->first();
|
|
|
|
if(isset($data['cover'])){
|
|
$data['cover'] = $this->saveImage('cover', 'articles/cover')[0] ?? '';
|
|
}
|
|
foreach ($data as $k => $v) {
|
|
if (!in_array($k, $columns)) {
|
|
continue;
|
|
}
|
|
|
|
$model->setAttribute($k, $v);
|
|
}
|
|
|
|
return $model->save();
|
|
}
|
|
|
|
|
|
public function hasRepeated($data, $id = 0): bool
|
|
{
|
|
$query = $this->query()->when($id, fn($query) => $query->where('id', '<>', $id));
|
|
|
|
if (isset($data['key']) && (clone $query)->where('key', $data['key'])->exists()) {
|
|
$this->setError('KEY重复');
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
|
|
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();
|
|
}
|
|
}
|