很多时候,数据都是有层级和分类的,使用laravel的Dcat框架,可以快速搭建一个结构清晰、且可以鼠标拖拽排序的后台;先上例子更直观:
这里是Dcat的模型树使用文档,戳一下;
重点注意事项有:
<?php
namespace App\Models\Demo;
use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use ModelTree;
protected $table = 'demo_categories';
// 父级ID字段名称,默认值为 parent_id
protected $parentColumn = 'pid';
// 排序字段名称,默认值为 order
protected $orderColumn = 'sort';
// 标题字段名称,默认值为 title
protected $titleColumn = 'name';
// Since v2.1.6-beta,定义depthColumn属性后,将会在数据表保存当前行的层级
protected $depthColumn = 'depth';
}
去 Dcat 后台用代码生成工具生成 Controller 文件,生成以后直接用我下面的代码覆盖:
<?php
namespace App\Admin\Controllers\SecondPhase;
use App\Models\CancerDetectionMethods;
use App\Models\CancerDetectionSamples;
use App\Models\CancerRecommendSearch;
use App\Models\CancerSiteInfo;
use App\Models\CancerSiteMethods;
use App\Models\CancerTargets;
use App\Models\LsDicLabel;
use App\Services\CancerTargetTreesService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Tree;
use Dcat\Admin\Widgets\Box;
use Dcat\Admin\Widgets\Form as WidgetForm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class CancerTargetsController extends AdminController
{
public function index(Content $content)
{
return $content
->title('模型树')
->body(function (Row $row) {
$row->column(6, $this->treeView()->render());
$row->column(6, function (Column $column) {
$form = new WidgetForm();
$form->action(admin_url('cancer-target-tree'));
$form->select('parent_id', '父级')->options(CancerTargets::selectOptions());
$form->text('title', '名称')->required();
$column->append(Box::make('新增', $form));
});
});
}
protected function treeView()
{
return new Tree(new CancerTargets(), function (Tree $tree) {
$tree->disableCreateButton();
$tree->disableQuickCreateButton();
$tree->disableEditButton();
$tree->maxDepth(4);
$tree->branch(function ($branch) {
$payload = $branch['id'].' - '.$branch['title'];
if ($branch['level'] === 4) {
$url = admin_url('/cancer-site/'.$branch['id'].'/edit');
$payload .= <<<HTML
<a href="$url" class="dd-nodrag">位点管理</a>
HTML;
}
return $payload;
});
});
}
protected function form()
{
return Form::make(new CancerTargets(), function (Form $form) {
$form->model()->with([
'methods:id, name',
]);
$form->display('id');
$form->select('parent_id', '父级')
->options(CancerTargets::selectOptions())
->saving(function ($v) {
return (int)$v;
});
$form->text('title', '名称')->required();
$form->hidden('level', '等级');
$form->disableViewButton();
$form->footer(function ($footer) {
// 去掉`重置`按钮
$footer->disableReset();
// 去掉`查看`checkbox
$footer->disableViewCheck();
// 去掉`继续编辑`checkbox
$footer->disableEditingCheck();
// 去掉`继续创建`checkbox
$footer->disableCreatingCheck();
// 设置`查看`默认选中
$footer->defaultViewChecked();
// 设置`继续编辑`默认选中
$footer->defaultEditingChecked();
// 设置`继续创建`默认选中
$footer->defaultCreatingChecked();
});
});
}
}