Admin.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. <?php
  2. namespace app\admin\controller\department;
  3. use app\admin\model\department\Department;
  4. use app\admin\model\department\Department as DepartmentModel;
  5. use app\common\controller\Backend;
  6. use \app\admin\model\department\Admin as DepartmentAdminModel;
  7. use \app\admin\model\department\AuthAdmin as AdminModel;
  8. use fast\Random;
  9. use fast\Tree;
  10. use think\Db;
  11. use think\Model;
  12. use think\Validate;
  13. /**
  14. * 部门成员
  15. */
  16. class Admin extends Backend
  17. {
  18. protected $tree = null;
  19. /**
  20. * 部门人员对象
  21. * @var null
  22. */
  23. protected $dadminModel = null;
  24. protected $childrenGroupIds = [];//权限组
  25. /**
  26. * 部门所有
  27. * @var array
  28. */
  29. protected $allDepartment = [];//
  30. protected $noNeedRight=['selectpage','getDepartmentIds'];
  31. public function _initialize()
  32. {
  33. parent::_initialize();
  34. $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
  35. $this->dadminModel = new DepartmentAdminModel;
  36. $departmentList = [];
  37. $this->allDepartment = \app\admin\model\department\Admin::getAllDepartmentsArray($this->auth->id,($this->auth->isSuperAdmin()||$this->auth->data_scope)?true:false);
  38. $this->allDepartment=collection($this->allDepartment)->toArray();
  39. $departmentdata = [];
  40. foreach ($this->allDepartment as $k => $v) {
  41. $state = ['opened' => true];
  42. $departmentList[] = [
  43. 'id' => $v['id'],
  44. 'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
  45. 'text' =>preg_replace('/&nbsp;|\s*|│|└|├\s*/','',__($v['name'])),//str_replace("&nbsp;",'', __($v['name'])) ,
  46. 'state' => $state
  47. ];
  48. }
  49. $tree = Tree::instance()->init($this->allDepartment, 'parent_id');
  50. $departmentOptions = $tree->getTree(0, "<option model='@model_id' value=@id @selected @disabled>@spacer@name</option>");
  51. $this->view->assign('departmentOptions', $departmentOptions);
  52. $this->assignconfig('departmentList', $departmentList);
  53. $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
  54. foreach ($result as $k => $v) {
  55. $departmentdata[$v['id']] = $v['name'];
  56. }
  57. $this->view->assign('departmentdata', $departmentdata);
  58. //兼容旧版本没有手机号
  59. $database=config('database');
  60. $exits_mobile=\think\Db::query("SELECT 1 FROM information_schema.COLUMNS WHERE table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
  61. $this->view->assign('exits_mobile', $exits_mobile?1:0);
  62. $this->assignconfig('exits_mobile', $exits_mobile?1:0);
  63. }
  64. /**
  65. * 成员列表
  66. */
  67. public function index()
  68. {
  69. //设置过滤方法
  70. $this->request->filter(['strip_tags']);
  71. $department_id = $this->request->request("department_id");
  72. if ($this->request->isAjax()) {
  73. $this->model = new \app\admin\model\department\AuthAdmin();
  74. $filter = $this->request->get("filter", '');
  75. $filter = (array)json_decode($filter, true);
  76. $filter_w = [];
  77. $authGroupList = \app\admin\model\AuthGroupAccess::field('uid,group_id')
  78. ->where('group_id', 'in', 8)
  79. ->select();
  80. foreach ($authGroupList as $k => $v) {
  81. $childrenAdminIds[] = $v['uid'];
  82. }
  83. $filter_w['id']=['in',$childrenAdminIds];
  84. if (isset($filter['department_id'])) {
  85. $department_id = $filter['department_id'];
  86. unset($filter['department_id']);
  87. $this->request->get(['filter' => json_encode($filter)]);
  88. }
  89. if ($department_id) {
  90. if (!in_array($department_id,array_column($this->allDepartment,'id'))){
  91. $this->error("您所选的部门没有权限");
  92. }
  93. $admin_ids = $this->dadminModel->where('department_id', 'in', $department_id)->column('admin_id');
  94. $filter_w['id'] = ['in', $admin_ids];
  95. }else if ($this->auth->data_scope!=1&&!$this->auth->isSuperAdmin()){
  96. $this->childrenAdminIds = \app\admin\model\department\Admin::getChildrenAdminIds($this->auth->id, true);
  97. $filter_w['admin_id']=['in',$this->childrenAdminIds];
  98. }
  99. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  100. $total = $this->model
  101. ->where($where)
  102. ->where($filter_w)
  103. ->order($sort, $order)->fetchSql(false)
  104. ->count();
  105. $list = $this->model
  106. ->where($where)
  107. ->with(['dadmin.department'])
  108. ->with(['groups.getGroup'])
  109. ->where($filter_w)
  110. ->order($sort, $order)
  111. ->limit($offset, $limit)->fetchSql(false)
  112. ->select();
  113. $result = array("total" => $total, "rows" => $list);
  114. return json($result);
  115. }
  116. return $this->view->fetch();
  117. }
  118. /**
  119. * 添加
  120. * @return string|\think\response\Json
  121. * @throws \think\Exception
  122. * @throws \think\db\exception\DataNotFoundException
  123. * @throws \think\db\exception\ModelNotFoundException
  124. * @throws \think\exception\DbException
  125. */
  126. public function add()
  127. {
  128. $groupdata = DepartmentModel::getGroupdata(
  129. $this->childrenGroupIds,
  130. $this->auth->isSuperAdmin() ? null : $this->auth->getGroups()
  131. );
  132. if ($this->request->isPost()) {
  133. $adminModel = new AdminModel();
  134. $departmentModel = new DepartmentModel();
  135. $params = $this->request->post("row/a");
  136. if ($params) {
  137. Db::startTrans();
  138. try {
  139. $department_id = $this->request->post("department_id/a");
  140. $is_principal = $this->request->post("is_principal",'0','intval');
  141. //获取部门信息
  142. if (!$department_id) {
  143. exception(__("组织不能为空"));
  144. }
  145. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  146. if (!$d_list) {
  147. exception(__("组织不能为空"));
  148. }
  149. if (!Validate::is($params['password'], '\S{6,16}')) {
  150. exception(__("Please input correct password"));
  151. }
  152. $params['salt'] = Random::alnum();
  153. $params['password'] = md5(md5($params['password']) . $params['salt']);
  154. $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
  155. $result = $adminModel->validate('Admin.add')->save($params);
  156. if ($result === false) {
  157. exception($adminModel->getError());
  158. }
  159. if (!$this->auth->isSuperAdmin()&&isset($params['data_scope'])){
  160. unset($params['data_scope']);//超级管理人才能赋予全部数据权限
  161. }
  162. $admin_id = $adminModel->id;
  163. $dadmin = array();
  164. //添加部门信息
  165. foreach ($d_list as $d_row) {
  166. $dadmin[] = ['is_principal'=>$is_principal==1?1:0,'department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $admin_id];
  167. }
  168. $this->dadminModel->saveAll($dadmin);
  169. $group = $this->request->post("group/a");
  170. //过滤不允许的组别,避免越权
  171. $group = [8];//array_intersect($this->childrenGroupIds, $group);
  172. //添加权限默认
  173. if (!$group) {
  174. exception(__('The parent group exceeds permission limit'));
  175. }
  176. $dataset = [];
  177. foreach ($group as $value) {
  178. $dataset[] = ['uid' => $admin_id, 'group_id' => $value];
  179. }
  180. model('AuthGroupAccess')->saveAll($dataset);
  181. Db::commit();
  182. } catch (\Exception $e) {
  183. Db::rollback();
  184. $this->error($e->getMessage());
  185. }
  186. $this->success();
  187. }
  188. $this->error(__('Parameter %s can not be empty', ''));
  189. }
  190. $this->view->assign('groupdata', $groupdata);
  191. return $this->view->fetch();
  192. }
  193. /**
  194. * 修改
  195. * @param null $ids
  196. * @return string|\think\response\Json
  197. * @throws \think\Exception
  198. * @throws \think\db\exception\DataNotFoundException
  199. * @throws \think\db\exception\ModelNotFoundException
  200. * @throws \think\exception\DbException
  201. */
  202. public function edit($ids = null)
  203. {
  204. $this->model = new AdminModel();
  205. $departmentModel = new DepartmentModel();
  206. $row = $this->model->get($ids);
  207. if (!$row) {
  208. $this->error(__('No Results were found'));
  209. }
  210. if (!\app\admin\model\department\Admin::checkDataAuth($this->auth,$row,'id')){
  211. $this->error(__('You have no permission'));
  212. }
  213. if ($this->request->isPost()) {
  214. //判断是不是超级管理员编辑
  215. if (!$this->auth->isSuperAdmin() && DepartmentAdminModel::isSuperAdmin($row->id)) {
  216. $this->error("您无权操作超级管理员");
  217. }
  218. $params = $this->request->post("row/a");
  219. if ($params) {
  220. Db::startTrans();
  221. try {
  222. $department_id = $this->request->post("department_id/a");
  223. //获取部门信息
  224. if (!$department_id) {
  225. exception(__("Department can't null"));
  226. }
  227. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  228. if (!$d_list) {
  229. exception(__("Department can't null"));
  230. }
  231. if ($params['password']) {
  232. if (!Validate::is($params['password'], '\S{6,16}')) {
  233. exception(__("Please input correct password"));
  234. }
  235. $params['salt'] = Random::alnum();
  236. $params['password'] = md5(md5($params['password']) . $params['salt']);
  237. } else {
  238. unset($params['password'], $params['salt']);
  239. }
  240. if (!$this->auth->isSuperAdmin()&&isset($params['data_scope'])){
  241. unset($params['data_scope']);//超级管理人才能赋予全部数据权限
  242. }
  243. //这里需要针对username和email做唯一验证
  244. $adminValidate = \think\Loader::validate('Admin');
  245. $adminValidate->rule([
  246. 'username' => 'require|regex:\w{3,20}|unique:admin,username,' . $row->id,
  247. // 'email' => 'require|email|unique:admin,email,' . $row->id,
  248. // 'mobile' => 'regex:1[3-9]\d{9}|unique:admin,mobile,' . $row->id,
  249. 'password' => 'regex:\S{32}',
  250. ]);
  251. $result = $row->validate('Admin.edit')->save($params);
  252. if ($result === false) {
  253. exception($row->getError());
  254. }
  255. $exist_departmentids = $this->dadminModel->where('admin_id', $row->id)->column('department_id');
  256. $dadmin = array();
  257. $deleteids = array_diff($exist_departmentids, $department_id);
  258. //添加部门信息
  259. foreach ($d_list as $d_row) {
  260. if (!in_array($d_row->id, $exist_departmentids)) {
  261. $dadmin[] = ['department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $row->id];
  262. }
  263. }
  264. if ($deleteids) {
  265. $this->dadminModel->where('admin_id', $row->id)->where('department_id', 'in', $deleteids)->delete();
  266. }
  267. if (count($dadmin) > 0) {
  268. $this->dadminModel->saveAll($dadmin);
  269. }
  270. // 先移除所有权限
  271. model('AuthGroupAccess')->where('uid', $row->id)->delete();
  272. $group = $this->request->post("group/a");
  273. // 过滤不允许的组别,避免越权
  274. $group = [8];//array_intersect($this->childrenGroupIds, $group);
  275. if (!$group) {
  276. exception(__('The parent group exceeds permission limit'));
  277. }
  278. $dataset = [];
  279. foreach ($group as $value) {
  280. $dataset[] = ['uid' => $row->id, 'group_id' => $value];
  281. }
  282. model('AuthGroupAccess')->saveAll($dataset);
  283. Db::commit();
  284. } catch (\Exception $e) {
  285. Db::rollback();
  286. $this->error($e->getMessage());
  287. }
  288. $this->success();
  289. }
  290. $this->error(__('Parameter %s can not be empty', ''));
  291. }
  292. $groupdata = DepartmentModel::getGroupdata(
  293. $this->childrenGroupIds,
  294. $this->auth->isSuperAdmin() ? null : $this->auth->getGroups()
  295. );
  296. $grouplist = $this->auth->getGroups($row['id']);
  297. $groupids = [];
  298. foreach ($grouplist as $k => $v) {
  299. $groupids[] = $v['id'];
  300. }
  301. $this->view->assign("groupids", $groupids);
  302. $this->view->assign('row', $row);
  303. $this->view->assign('department_ids', $this->dadminModel->getDepartmentIds($ids));
  304. $this->view->assign('groupdata', $groupdata);
  305. return $this->view->fetch();
  306. }
  307. /**
  308. * 删除
  309. */
  310. public function del($ids = "")
  311. {
  312. if (!$this->request->isPost()) {
  313. $this->error(__("Invalid parameters"));
  314. }
  315. $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
  316. $this->model = new AdminModel();
  317. $ids = $ids ? $ids : $this->request->post("ids");
  318. if ($ids) {
  319. $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
  320. // 避免越权删除管理员
  321. $childrenGroupIds = $this->childrenGroupIds;
  322. $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
  323. $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
  324. })->select();
  325. if ($adminList) {
  326. $deleteIds = [];
  327. foreach ($adminList as $k => $v) {
  328. $deleteIds[] = $v->id;
  329. }
  330. $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
  331. if ($deleteIds) {
  332. Db::startTrans();
  333. try {
  334. $this->model->destroy($deleteIds);
  335. model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
  336. //删除部门员工信息
  337. $this->dadminModel->where('admin_id', 'in', $deleteIds)->delete();;
  338. Db::commit();
  339. } catch (\Exception $e) {
  340. Db::rollback();
  341. $this->error($e->getMessage());
  342. }
  343. $this->success();
  344. }
  345. $this->error(__('No rows were deleted'));
  346. }
  347. }
  348. $this->error(__('You have no permission'));
  349. }
  350. /**
  351. * 批量更新
  352. */
  353. public function multi($ids = "")
  354. {
  355. $this->model = new AdminModel();
  356. return parent::multi($ids);
  357. }
  358. /**
  359. * 设置部门负责人
  360. */
  361. public function principal($ids = "")
  362. {
  363. $this->model = new AdminModel();
  364. $departmentModel = new DepartmentModel();
  365. $row = $this->model->get($ids);
  366. if ($this->request->isPost()) {
  367. //判断是不是超级管理员编辑
  368. if (!DepartmentAdminModel::isSuperAdmin($this->auth->id) && DepartmentAdminModel::isSuperAdmin($row->id)) {
  369. $this->error("您无权操作超级管理员");
  370. }
  371. $department_id = $this->request->post("department_id/a");
  372. if ($department_id && $department_id[0]) {
  373. Db::startTrans();
  374. try {
  375. $d_list = $departmentModel->where('id', 'in', $department_id)->select();
  376. if (!$d_list) {
  377. exception(__("Department can't null"));
  378. }
  379. //先移除他所有负责的部门
  380. $this->dadminModel->where('admin_id', $row->id)->update(['is_principal' => 0]);
  381. //判断选择的部门是否存在,不存在就先把他加入
  382. $p_departmentids = array_column($d_list, 'id');
  383. $exist_departmentids = $this->dadminModel->where('admin_id', $row->id)->column('department_id');
  384. $dadmin = array();
  385. //添加部门信息
  386. foreach ($d_list as $d_row) {
  387. if (!in_array($d_row->id, $exist_departmentids)) {
  388. $dadmin[] = ['department_id' => $d_row->id, 'organise_id' => $d_row->organise_id ? $d_row->organise_id : $d_row->id, 'admin_id' => $row->id];
  389. }
  390. }
  391. if (count($dadmin) > 0) {
  392. $this->dadminModel->saveAll($dadmin);
  393. }
  394. //更改为负责人
  395. $this->dadminModel->where('admin_id', $row->id)->where('department_id', 'in', $p_departmentids)->update(['is_principal' => 1]);
  396. Db::commit();
  397. } catch (\Exception $e) {
  398. Db::rollback();
  399. $this->error($e->getMessage());
  400. }
  401. } else {
  402. //移除他所有负责的部门
  403. $this->dadminModel->where('admin_id', $row->id)->update(['is_principal' => 0]);
  404. }
  405. $this->success();
  406. }
  407. $this->view->assign('row', $row);
  408. $this->view->assign('department_ids', $this->dadminModel::getPrincipalIds($ids));
  409. return $this->view->fetch();
  410. }
  411. /**
  412. * 获取员工的部门IDs
  413. */
  414. public function getDepartmentIds($id = ""){
  415. $departmentIds=DepartmentAdminModel::getDepartmentIds($id);
  416. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  417. $this->success("",'',['departmentIds' => $departmentIds]);
  418. }
  419. /**
  420. * 下拉选择
  421. * @Internal
  422. */
  423. public function selectpage()
  424. {
  425. $type=$this->request->request('type');//all代表选择所有
  426. $custom = ['status' => 'normal'];
  427. if ($type != "all") {
  428. $childrenAdminIds = \app\admin\model\department\Admin::getChildrenAdminIds($this->auth->id, true);
  429. $custom['id'] = ['in', $childrenAdminIds];
  430. }
  431. $this->selectpageFields = ['id', 'concat(nickname,"(",id,")") as nickname'];
  432. $this->request->request(['custom' => $custom]);
  433. //搜索字段
  434. $searchfield = (array)$this->request->request("searchField/a");
  435. $searchfield[]='id';
  436. $this->request->request(['searchField'=>$searchfield]);
  437. $this->model = model('admin');
  438. //设置过滤方法
  439. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  440. //搜索关键词,客户端输入以空格分开,这里接收为数组
  441. $word = (array)$this->request->request("q_word/a");
  442. //当前页
  443. $page = $this->request->request("pageNumber");
  444. //分页大小
  445. $pagesize = $this->request->request("pageSize");
  446. //搜索条件
  447. $andor = $this->request->request("andOr", "and", "strtoupper");
  448. //排序方式
  449. $orderby = (array)$this->request->request("orderBy/a");
  450. //显示的字段
  451. $field = $this->request->request("showField");
  452. //主键
  453. $primarykey = $this->request->request("keyField");
  454. //主键值
  455. $primaryvalue = $this->request->request("keyValue");
  456. //搜索字段
  457. $searchfield = (array)$this->request->request("searchField/a");
  458. //自定义搜索条件
  459. $custom = (array)$this->request->request("custom/a");
  460. //是否返回树形结构
  461. $istree = $this->request->request("isTree", 0);
  462. $ishtml = $this->request->request("isHtml", 0);
  463. if ($istree) {
  464. $word = [];
  465. $pagesize = 999999;
  466. }
  467. $order = [];
  468. foreach ($orderby as $k => $v) {
  469. $order[$v[0]] = $v[1];
  470. }
  471. $field = $field ? $field : 'name';
  472. //如果有primaryvalue,说明当前是初始化传值
  473. if ($primaryvalue !== null) {
  474. $where = [$primarykey => ['in', $primaryvalue]];
  475. $pagesize = 999999;
  476. } else {
  477. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  478. $logic = $andor == 'AND' ? '&' : '|';
  479. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  480. $searchfield = str_replace(',', $logic, $searchfield);
  481. $word = array_filter(array_unique($word));
  482. if (count($word) == 1) {
  483. $query->where($searchfield, "like", "%" . reset($word) . "%");
  484. } else {
  485. $query->where(function ($query) use ($word, $searchfield) {
  486. foreach ($word as $index => $item) {
  487. $query->whereOr(function ($query) use ($item, $searchfield) {
  488. $query->where($searchfield, "like", "%{$item}%");
  489. });
  490. }
  491. });
  492. }
  493. if ($custom && is_array($custom)) {
  494. foreach ($custom as $k => $v) {
  495. if (is_array($v) && 2 == count($v)) {
  496. $query->where($k, trim($v[0]), $v[1]);
  497. } else {
  498. $query->where($k, '=', $v);
  499. }
  500. }
  501. }
  502. };
  503. }
  504. $adminIds = $this->getDataLimitAdminIds();
  505. if (is_array($adminIds)) {
  506. $this->model->where($this->dataLimitField, 'in', $adminIds);
  507. }
  508. $list = [];
  509. $total = $this->model->where($where)->count();
  510. if ($total > 0) {
  511. if (is_array($adminIds)) {
  512. $this->model->where($this->dataLimitField, 'in', $adminIds);
  513. }
  514. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  515. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  516. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  517. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  518. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  519. $primaryvalue = array_map(function ($value) {
  520. return '\'' . $value . '\'';
  521. }, $primaryvalue);
  522. $primaryvalue = implode(',', $primaryvalue);
  523. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  524. } else {
  525. $this->model->order($order);
  526. }
  527. $datalist = $this->model->where($where)
  528. ->field($this->selectpageFields)
  529. ->page($page, $pagesize)
  530. ->select();
  531. foreach ($datalist as $index => $item) {
  532. unset($item['password'], $item['salt']);
  533. if ($this->selectpageFields == '*') {
  534. $result = [
  535. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  536. $field => isset($item[$field]) ? $item[$field] : '',
  537. ];
  538. } else {
  539. $result = (($item instanceof Model ? $item->toArray() : (array)$item));
  540. }
  541. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  542. $list[] = $result;
  543. }
  544. if ($istree && !$primaryvalue) {
  545. $tree = Tree::instance();
  546. $tree->init(collection($list)->toArray(), 'pid');
  547. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  548. if (!$ishtml) {
  549. foreach ($list as &$item) {
  550. $item = str_replace('&nbsp;', ' ', $item);
  551. }
  552. unset($item);
  553. }
  554. }
  555. }
  556. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  557. return json(['list' => $list, 'total' => $total]);
  558. }
  559. }