UserRule.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace app\admin\model;
  3. use fast\Tree;
  4. use think\Model;
  5. class UserRule extends Model
  6. {
  7. // 表名
  8. protected $name = 'user_rule';
  9. // 自动写入时间戳字段
  10. protected $autoWriteTimestamp = 'int';
  11. // 定义时间戳字段名
  12. protected $createTime = 'createtime';
  13. protected $updateTime = 'updatetime';
  14. // 追加属性
  15. protected $append = [
  16. 'status_text'
  17. ];
  18. protected static function init()
  19. {
  20. self::afterInsert(function ($row) {
  21. if (!$row['weigh']) {
  22. $pk = $row->getPk();
  23. $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
  24. }
  25. });
  26. }
  27. public function getTitleAttr($value, $data)
  28. {
  29. return __($value);
  30. }
  31. public function getStatusList()
  32. {
  33. return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
  34. }
  35. public function getStatusTextAttr($value, $data)
  36. {
  37. $value = $value ? $value : $data['status'];
  38. $list = $this->getStatusList();
  39. return $list[$value] ?? '';
  40. }
  41. public static function getTreeList($selected = [])
  42. {
  43. $ruleList = collection(self::where('status', 'normal')->order('weigh desc,id desc')->select())->toArray();
  44. $nodeList = [];
  45. Tree::instance()->init($ruleList);
  46. $ruleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
  47. $hasChildrens = [];
  48. foreach ($ruleList as $k => $v)
  49. {
  50. if ($v['haschild'])
  51. $hasChildrens[] = $v['id'];
  52. }
  53. foreach ($ruleList as $k => $v) {
  54. $state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens));
  55. $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
  56. }
  57. return $nodeList;
  58. }
  59. }