模型树

这个功能可以实现一个树状组件,可以用拖拽的方式实现数据的层级、排序等操作,下面是基本的用法。

模型树 - 图1

表结构和模型

要使用model-tree,要遵守约定的表结构:

{tip} parent_id字段一定要默认为0!!!

  1. CREATE TABLE `demo_categories` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `parent_id` int(11) NOT NULL DEFAULT '0',
  4. `order` int(11) NOT NULL DEFAULT '0',
  5. `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  6. `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  7. `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

上面的表格结构里面有三个必要的字段parent_idordertitle,其它字段没有要求。

对应的模型为app/Models/Category.php:

  1. <?php
  2. namespace App\Models\Demo;
  3. use Dcat\Admin\Traits\ModelTree;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Category extends Model
  6. {
  7. use ModelTree;
  8. protected $table = 'demo_categories';
  9. }

表结构中的三个字段parent_idordertitle的字段名也是可以修改的:

{tip} 为了便于阅读,这里不再展示 Repository 代码。

  1. <?php
  2. namespace App\Models\Demo;
  3. use Dcat\Admin\Traits\ModelTree;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Category extends Model
  6. {
  7. use ModelTree;
  8. protected $table = 'demo_categories';
  9. // 父级ID字段名称,默认值为 parent_id
  10. protected $parentColumn = 'pid';
  11. // 排序字段名称,默认值为 order
  12. protected $orderColumn = 'sort';
  13. // 标题字段名称,默认值为 title
  14. protected $titleColumn = 'name';
  15. }

使用方法

然后就是在页面中使用model-tree了:

  1. <?php
  2. namespace App\Admin\Controllers\Demo;
  3. use App\Models\Category;
  4. use Dcat\Admin\Layout\Row;
  5. use Dcat\Admin\Layout\Content;
  6. use Dcat\Admin\Tree;
  7. use Dcat\Admin\Controllers\AdminController;
  8. class CategoryController extends AdminController
  9. {
  10. public function index(Content $content)
  11. {
  12. return $content->header('树状模型')
  13. ->body(function (Row $row) {
  14. $tree = new Tree(new Category);
  15. $row->column(12, $tree);
  16. });
  17. }
  18. }

可以通过下面的方式来修改行数据的显示:

  1. $tree = new Tree(new Category);
  2. $tree->branch(function ($branch) {
  3. $src = config('admin.upload.host') . '/' . $branch['logo'] ;
  4. $logo = "<img src='$src' style='max-width:30px;max-height:30px' class='img'/>";
  5. return "{$branch['id']} - {$branch['title']} $logo";
  6. });

在回调函数中返回的字符串类型数据,就是在树状组件中的每一行的显示内容,$branch参数是当前行的数据数组。

如果要修改模型的查询,用下面的方式

  1. $tree->query(function ($model) {
  2. return $model->where('type', 1);
  3. });

自定义工具栏按钮

请参考文档模型树动作