Category.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Model;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Encore\Admin\Traits\AdminBuilder;
  5. use Encore\Admin\Traits\ModelTree;
  6. class Category extends Model
  7. {
  8. use ModelTree,AdminBuilder;
  9. public $table = "jm_category";
  10. protected $fillable = ['parent_id' , 'category_name' , 'id'];
  11. // 展示树状调用
  12. public function __construct(array $attributes = [])
  13. {
  14. parent::__construct($attributes);
  15. $this->setParentColumn('parent_id');
  16. $this->setOrderColumn( 'id');
  17. $this->setTitleColumn( 'category_name');
  18. }
  19. // 获取分类名称
  20. public static function getCategoryName($parent_id)
  21. {
  22. $category = self::find($parent_id);
  23. return $category->category_name;
  24. }
  25. public static function getCategory()
  26. {
  27. return self::getTree(self::all() , 0, 0);
  28. }
  29. public static function getTree($arr , $pid , $step)
  30. {
  31. global $tree;
  32. //$arr = self::all();
  33. if($arr->isEmpty()) {
  34. return [];
  35. } else {
  36. foreach ($arr as $key => $val) {
  37. if ($val['parent_id'] == $pid) {
  38. $flg = str_repeat('└-', $step);
  39. $val['category_name'] = $flg . $val['category_name'];
  40. $tree[] = $val;
  41. self::getTree($arr , $val['id'], $step + 1);
  42. }
  43. }
  44. if(empty($tree)) return [0 => '1级'];
  45. $selectOption = [];
  46. foreach ($tree as $option) {
  47. $selectOption[$option->id] = $option->category_name;
  48. }
  49. $selectOption[0] = 'Root';
  50. return $selectOption;
  51. }
  52. }
  53. }