laravel-admin 二级联动+无限极分类

学校班级二级联动

StudentController.php

$form->select('school_id', '学校')->options(
    School::all()->pluck('name','id'))
    ->load('class_id', '/admin/classList');

$form->select('class_id','班级')->options(function ($id) {
    return  Classs::where('id',$id)->pluck('name', 'id');
});

路由-添加联动方法 app\admin\route.php

$router->get('classList','StudentController@classList');

联动方法 StudentController.php

public function classList(Request $request){
    $projectId = $request->get('q');
    return Classs::where('sid',$projectId)->get(['id', DB::raw('name as text')]);
}

无限极分类及接口

CateController.php

<?php


namespace App\Admin\Controllers;


use App\Models\Cate;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Layout\{Column, Row, Content};
use Encore\Admin\{Tree,Form};
use Encore\Admin\Widgets\Box;

/**
* 分类管理
* @package App\Admin\Controllers
*/
class CateController extends Content
{
    use HasResourceActions;

    protected $title = '分类';

    /**
     * 首页
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content->title('分类')
            ->description('列表')
            ->row(function (Row $row){
                // 显示分类树状图
                $row->column(6, $this->treeView()->render());


                $row->column(6, function (Column $column){
                    $form = new \Encore\Admin\Widgets\Form();
                    $form->action(admin_url('cates'));
                    $form->select('pid', '分类')->options(Cate::selectOptions());
                    $form->text('title', '名称')->required();
                    $form->number('sort', '排序')->default(99)->help('越小越靠前');
                    $column->append((new Box(__('添加分类'), $form))->style('success'));
                });


            });
    }

    /**
     * 树状视图
     * @return Tree
     */
    protected function treeView()
    {
        return  Cate::tree(function (Tree $tree){
            $tree->disableCreate(); // 关闭新增按钮
            $tree->branch(function ($branch) {
                return "<strong>{$branch['title']}</strong>"; // 标题添加strong标签
            });
        });
    }

    /**
     * 编辑
     * @param $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content->title(__('Cate'))
            ->description(__('edit'))
            ->row($this->form()->edit($id));
    }


    /**
     * 表单
     * @return Form
     */
    public function form()
    {
        $form = new Form(new Cate());


        //$form->display('id', 'ID');
        $form->select('pid', '分类')->options(Cate::selectOptions());
        $form->text('title', '名称')->required();
        $form->number('sort', '排序')->default(99)->help('越小越靠前');


        $form->tools(function (Form\Tools $tools) {
            //$tools->disableList();
            $tools->disableDelete();
            $tools->disableView();
        
        });
        $form->footer(function ($footer) {
            $footer->disableReset();
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
        
        });

        return $form;
    }

}

模型

<?php

namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;


class Cate extends Model
{
    use ModelTree,AdminBuilder;  // 使用laravel-admin 的 tree


    //protected $table = 'cate';
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);


        $this->setParentColumn('pid'); // 设置父类ID的字段名称
        $this->setOrderColumn('sort'); // 设置排序字段名称
        $this->setTitleColumn('title'); // 设置标题名称
    }


    /**
     * 该分类的子分类
     */
    public function child()
    {
        return $this->hasMany(get_class($this), 'pid', $this->getKeyName());
    }


    /**
     * 该分类的父分类
     */
    public function parent()
    {
        return $this->hasOne(get_class($this), $this->getKeyName(), 'pid');
    }
}

无限极分类接口

<?php
namespace App\Http\Controllers\Api;
  
use Illuminate\Http\Request;
use App\Models\Cate;

class CateController extends ApiController
{
    function getTree($id,$array){
        //第一步 构造数据
        $items = array();
        foreach($array as $value){
            $items[$value['id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach($items as $key => $value){
            if(isset($items[$value['pid']])){
                    $items[$value['pid']]['son'][] = &$items[$key];
            }else{
                if((empty($id))||($id==$value['id']))
                    $tree[] = &$items[$key];
            }   
        }
        return $tree;
    }
    
    //无限极分类接口
    public function cates(Request $request)
    {
        $id = $request->id;
        $data = Cate::all()->toArray();
        return $this->success($this->getTree($id,$data));
    }

}

测试接口

不传1级id输出全部分类

传1级id查出此id下列表

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Laravel 中,实现无限级分类可以使用递归关联来完成。具体来说,我们可以使用一个 `Category` 模型来表示分类,每个分类包含一个 `parent_id` 字段来表示其父分类的 ID。如果 `parent_id` 为 0,则表示该分类为顶级分类。然后,我们可以在 `Category` 模型中定义一个 `children` 方法来表示其子分类,如下所示: ```php class Category extends Model { public function children() { return $this->hasMany(Category::class, 'parent_id'); } } ``` 在上面的代码中,我们使用 `hasMany` 方法来定义 `Category` 模型与自身的一对多关系。具体来说,我们将 `Category` 模型作为第一个参数传递给 `hasMany` 方法,表示我们要关联的模型是 `Category`,然后将 `parent_id` 字段作为第二个参数传递给 `hasMany` 方法,表示我们要使用 `parent_id` 字段来关联两个模型。这样,我们就可以通过 `$category->children` 来获取该分类的所有子分类了。 接下来,我们可以使用递归函数来遍历无限级分类。具体来说,我们可以定义一个名为 `getTree` 的静态方法,该方法接受一个 `$parentId` 参数表示要获取的分类的父分类 ID,然后返回一个包含所有子分类分类树数组。实现代码如下: ```php class Category extends Model { public function children() { return $this->hasMany(Category::class, 'parent_id'); } public static function getTree($parentId = 0) { $categories = self::where('parent_id', $parentId)->get(); $tree = []; foreach ($categories as $category) { $tree[] = [ 'id' => $category->id, 'name' => $category->name, 'children' => self::getTree($category->id), ]; } return $tree; } } ``` 在上面的代码中,我们首先使用 `where` 方法来获取指定父分类 ID 的所有分类,然后使用 `foreach` 循环遍历这些分类,构建分类树数组。具体来说,我们将每个分类的 ID 和名称添加到数组中,并递归调用 `getTree` 方法来获取该分类的子分类。最后,我们返回分类树数组。 使用上面的代码,我们可以轻松地获取无限级分类。例如,要获取所有顶级分类及其子分类,可以这样写: ```php $categories = Category::getTree(); ``` 要获取指定分类及其子分类,可以这样写: ```php $categories = Category::getTree($categoryId); ``` 其中,`$categoryId` 表示指定分类的 ID。 需要注意的是,上面的代码虽然简单,但在处理大量分类时可能会导致性能问题。因此,建议在数据库中添加一个 `depth` 字段来表示分类的深度,然后在查询分类时使用 `withDepth` 方法来预加载分类的深度,以便更高效地处理大量分类。具体来说,我们可以这样定义 `Category` 模型: ```php class Category extends Model { public function children() { return $this->hasMany(Category::class, 'parent_id'); } public function parent() { return $this->belongsTo(Category::class, 'parent_id'); } public function scopeWithDepth($query) { $table = $this->getTable(); $query->selectRaw("{$table}.*, (SELECT COUNT(*) FROM {$table} AS t WHERE t.id = {$table}.id OR t.{$this->getKeyName()} = {$table}.{$this->getKeyName()}) AS depth"); } } ``` 在上面的代码中,我们定义了一个名为 `withDepth` 的本地作用域,该作用域使用 `selectRaw` 方法来查询分类及其深度。具体来说,我们使用 `COUNT(*)` 函数来统计分类的深度,并将结果保存到 `depth` 字段中。这样,在查询分类时,我们就可以使用 `$query->withDepth()` 方法来预加载分类的深度了。例如,要获取所有分类及其深度,可以这样写: ```php $categories = Category::withDepth()->get(); ``` 获取分类深度后,我们就可以使用递归函数来遍历分类树了。具体来说,我们可以修改 `getTree` 方法,将分类深度作为第二个参数传递给该方法,然后使用 `$category->depth` 来判断分类的深度。如果分类的深度等于指定深度,则将该分类添加到分类树数组中。实现代码如下: ```php class Category extends Model { public function children() { return $this->hasMany(Category::class, 'parent_id'); } public function parent() { return $this->belongsTo(Category::class, 'parent_id'); } public function scopeWithDepth($query) { $table = $this->getTable(); $query->selectRaw("{$table}.*, (SELECT COUNT(*) FROM {$table} AS t WHERE t.id = {$table}.id OR t.{$this->getKeyName()} = {$table}.{$this->getKeyName()}) AS depth"); } public static function getTree($parentId = 0, $depth = null) { $query = self::where('parent_id', $parentId); if ($depth !== null) { $query->where('depth', $depth); } $categories = $query->get(); $tree = []; foreach ($categories as $category) { if ($depth === null || $category->depth == $depth) { $tree[] = [ 'id' => $category->id, 'name' => $category->name, 'children' => self::getTree($category->id, $depth !== null ? $depth + 1 : null), ]; } } return $tree; } } ``` 在上面的代码中,我们首先修改 `getTree` 方法,将分类深度作为第二个参数传递给该方法。然后,在查询分类时,我们使用 `where` 方法来限制分类的深度。如果指定了分类深度,则只查询指定深度的分类;否则,查询所有分类。最后,在遍历分类时,我们使用 `$category->depth` 来判断分类的深度,如果分类的深度等于指定深度,则将该分类添加到分类树数组中。 使用上面的代码,我们可以轻松地获取无限级分类。例如,要获取所有顶级分类及其子分类,可以这样写: ```php $categories = Category::getTree(); ``` 要获取指定分类及其子分类,可以这样写: ```php $categories = Category::getTree($categoryId); ``` 其中,`$categoryId` 表示指定分类的 ID。如果要获取指定深度的分类,可以将深度作为第三个参数传递给 `getTree` 方法,例如: ```php $categories = Category::getTree(0, 2); ``` 这样,就可以获取所有顶级分类及其子分类的前两级了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值