generated from liutk/owl-admin-base
95 lines
2.3 KiB
PHP
95 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Services;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Arr;
|
|
use Slowlyo\OwlAdmin\Admin;
|
|
use Slowlyo\OwlAdmin\Models\AdminMenu;
|
|
|
|
/**
|
|
* @method AdminMenu getModel()
|
|
* @method AdminMenu|Builder query()
|
|
*/
|
|
class AdminMenuService extends BaseService
|
|
{
|
|
public function __construct()
|
|
{
|
|
$this->modelName = Admin::adminMenuModel();
|
|
}
|
|
|
|
public function getTree(): array
|
|
{
|
|
$list = $this->query()->orderBy('order')->get()->toArray();
|
|
|
|
return array2tree($list);
|
|
}
|
|
|
|
public function parentIsChild($id, $parent_id): bool
|
|
{
|
|
$parent = $this->query()->find($parent_id);
|
|
|
|
do {
|
|
if ($parent->parent_id == $id) {
|
|
return true;
|
|
}
|
|
// 如果没有parent 则为顶级菜单 退出循环
|
|
$parent = $parent->parent;
|
|
} while ($parent);
|
|
|
|
return false;
|
|
}
|
|
|
|
public function update($primaryKey, $data): bool
|
|
{
|
|
$columns = $this->getTableColumns();
|
|
|
|
$parent_id = Arr::get($data, 'parent_id');
|
|
if ($parent_id != 0) {
|
|
amis_abort_if($this->parentIsChild($primaryKey, $parent_id), __('admin.admin_menu.parent_id_not_allow'));
|
|
}
|
|
|
|
$model = $this->query()->whereKey($primaryKey)->first();
|
|
|
|
return $this->saveData($data, $columns, $model);
|
|
}
|
|
|
|
public function store($data): bool
|
|
{
|
|
$columns = $this->getTableColumns();
|
|
|
|
$model = $this->getModel();
|
|
|
|
return $this->saveData($data, $columns, $model);
|
|
}
|
|
|
|
public function changeHomePage($excludeId = 0)
|
|
{
|
|
$this->query()->when($excludeId, fn ($query) => $query->where('id', '<>', $excludeId))->update(['is_home' => 0]);
|
|
}
|
|
|
|
public function list()
|
|
{
|
|
return ['items' => $this->getTree()];
|
|
}
|
|
|
|
protected function saveData($data, array $columns, AdminMenu $model): bool
|
|
{
|
|
foreach ($data as $k => $v) {
|
|
if (! in_array($k, $columns)) {
|
|
continue;
|
|
}
|
|
|
|
$v = $k == 'parent_id' ? intval($v) : $v;
|
|
|
|
$model->setAttribute($k, $v);
|
|
|
|
if ($k == 'is_home' && $v == 1) {
|
|
$this->changeHomePage($model->getKey());
|
|
}
|
|
}
|
|
|
|
return $model->save();
|
|
}
|
|
}
|