【laravel5.4】Baum无限极分类和collect助手函数、transform()中间件(转换数据)方法使用

1、目的,无限极分类

/* 
     * getdepartment:获取【当前登录用户对应公司的所有有效部门】
     * DB::table ==>返回查询构造器结果,不会返回一个collect实例
     * 而 【默认情况下,Eloquent 查询的结果总是返回 Collection 实例】
     * 进行transform操作
     * add by Daisheng  2018/04/03
     */
    public function getdepartment(Request $request)
    {
        $department = DB::table('departments')
            ->select('departments.*', 'd.dep_name as parent_name')
            ->leftJoin('departments as d', 'd.id', '=', 'departments.parent_id')
            ->where('departments.company_id',$this->company_id)
            ->orderBy('departments.lft')
            ->get();
        /*
         * collect():全局助手函数,将放入的数据转换成集合对象 instance
         */
        $department = collect($department); 
        /* 
         * transform():全局中间件TransformsRequest的方法,递归处理请求数据格式
         */
        $department->transform(function ($item, $key) {
            $item->parent_name = $item->parent_name ? $item->parent_name : '/';
            $item->dep_name = str_repeat('—', $item->depth) . $item->dep_name;
            return $item;
        });
        return $department;
    }
    
    /* 
     * model::create([]):方法返回被插入的模型实例。但是,在此之前,你需要指定模型的 fillable 或 guarded 属性
     * 参考http://laravelacademy.org/post/6979.html
     * model继承baum
ode类库的makeChildOf() 建立插入模型和parent模型对象之间的关系
     */
    public function departmentstore(Request $request)
    {
        $parent_id = $request->parent_id ? $request->parent_id : 0;
        //返回被插入的模型实例对象
        $dep_name = Department::create(['dep_name' => $request->dep_name,'company_id'=>$this->company_id]);
        if ($parent_id) {
            //返回当前实例的parent_id对应的模型实例
            $parent = Department::where('id', '=', $parent_id)->first();
            //通过model继承baum
ode类库的makeChildOf() 建立插入模型和parent模型对象之间的关系
            $dep_name->makeChildOf($parent);
        } else {
            $dep_name->save();
        }
        echo 1;
    }
原文地址:https://www.cnblogs.com/xuzhengzong/p/8709796.html