I have a table that is a tree classification table. up_id corresponds to the superior classification id. I just want to convert up_id to the name of the superior classification when displaying it in the table. What should I do? I think it can be implemented using the model's getter, but I don't know how to use it
The controller method for table data is like this
//返回分类列表数据 if(Request::isAjax()) { $list = ModelTree::order(['up_id','sort','id']) ->paginate($this->request->get('limit', 20)); $data = [ 'code' => 0, 'msg' => '正在请求中...', 'count' =>$list->count(), 'data' => $list->items() ]; return Json::create($data); }
清风2020-02-08 13:02:26
The problem is solved, haha
How to write the model getter
//上级分类名称获取器 public function getUpNameAttr($value,$data) { $list = Tree::field(['name'])->where('id','=',$data['up_id'])->find(); if($list) { return $list['name']; }else{ return '顶级分类'; } }
How to write the controller
//返回分类列表数据 if(Request::isAjax()) { $list = ModelTree::order(['up_id','sort','id']) ->paginate($this->request->get('limit', 20)); foreach ($list as $item) { $item->append(['up_name']); $item['up_name'] = $item->up_name; } $data = [ 'code' => 0, 'msg' => '正在请求中...', 'count' =>$list->count(), 'data' => $list->items() ]; return Json::create($data); }
Display the result