ModelTree.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. namespace Encore\Admin\Traits;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Request;
  6. trait ModelTree
  7. {
  8. /**
  9. * @var array
  10. */
  11. protected static $branchOrder = [];
  12. /**
  13. * @var string
  14. */
  15. protected $parentColumn = 'parent_id';
  16. /**
  17. * @var string
  18. */
  19. protected $titleColumn = 'title';
  20. /**
  21. * @var string
  22. */
  23. protected $orderColumn = 'order';
  24. /**
  25. * @var \Closure
  26. */
  27. protected $queryCallback;
  28. /**
  29. * Get children of current node.
  30. *
  31. * @return \Illuminate\Database\Eloquent\Relations\HasMany
  32. */
  33. public function children()
  34. {
  35. return $this->hasMany(static::class, $this->parentColumn);
  36. }
  37. /**
  38. * Get parent of current node.
  39. *
  40. * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
  41. */
  42. public function parent()
  43. {
  44. return $this->belongsTo(static::class, $this->parentColumn);
  45. }
  46. /**
  47. * @return string
  48. */
  49. public function getParentColumn()
  50. {
  51. return $this->parentColumn;
  52. }
  53. /**
  54. * Set parent column.
  55. *
  56. * @param string $column
  57. */
  58. public function setParentColumn($column)
  59. {
  60. $this->parentColumn = $column;
  61. }
  62. /**
  63. * Get title column.
  64. *
  65. * @return string
  66. */
  67. public function getTitleColumn()
  68. {
  69. return $this->titleColumn;
  70. }
  71. /**
  72. * Set title column.
  73. *
  74. * @param string $column
  75. */
  76. public function setTitleColumn($column)
  77. {
  78. $this->titleColumn = $column;
  79. }
  80. /**
  81. * Get order column name.
  82. *
  83. * @return string
  84. */
  85. public function getOrderColumn()
  86. {
  87. return $this->orderColumn;
  88. }
  89. /**
  90. * Set order column.
  91. *
  92. * @param string $column
  93. */
  94. public function setOrderColumn($column)
  95. {
  96. $this->orderColumn = $column;
  97. }
  98. /**
  99. * Set query callback to model.
  100. *
  101. * @param \Closure|null $query
  102. *
  103. * @return $this
  104. */
  105. public function withQuery(\Closure $query = null)
  106. {
  107. $this->queryCallback = $query;
  108. return $this;
  109. }
  110. /**
  111. * Format data to tree like array.
  112. *
  113. * @return array
  114. */
  115. public function toTree()
  116. {
  117. return $this->buildNestedArray();
  118. }
  119. /**
  120. * Build Nested array.
  121. *
  122. * @param array $nodes
  123. * @param int $parentId
  124. *
  125. * @return array
  126. */
  127. protected function buildNestedArray(array $nodes = [], $parentId = 0)
  128. {
  129. $branch = [];
  130. if (empty($nodes)) {
  131. $nodes = $this->allNodes();
  132. }
  133. foreach ($nodes as $node) {
  134. if ($node[$this->parentColumn] == $parentId) {
  135. $children = $this->buildNestedArray($nodes, $node[$this->getKeyName()]);
  136. if ($children) {
  137. $node['children'] = $children;
  138. }
  139. $branch[] = $node;
  140. }
  141. }
  142. return $branch;
  143. }
  144. /**
  145. * Get all elements.
  146. *
  147. * @return mixed
  148. */
  149. public function allNodes()
  150. {
  151. $orderColumn = DB::getQueryGrammar()->wrap($this->orderColumn);
  152. $byOrder = $orderColumn.' = 0,'.$orderColumn;
  153. $self = new static();
  154. if ($this->queryCallback instanceof \Closure) {
  155. $self = call_user_func($this->queryCallback, $self);
  156. }
  157. return $self->orderByRaw($byOrder)->get()->toArray();
  158. }
  159. /**
  160. * Set the order of branches in the tree.
  161. *
  162. * @param array $order
  163. *
  164. * @return void
  165. */
  166. protected static function setBranchOrder(array $order)
  167. {
  168. static::$branchOrder = array_flip(array_flatten($order));
  169. static::$branchOrder = array_map(function ($item) {
  170. return ++$item;
  171. }, static::$branchOrder);
  172. }
  173. /**
  174. * Save tree order from a tree like array.
  175. *
  176. * @param array $tree
  177. * @param int $parentId
  178. */
  179. public static function saveOrder($tree = [], $parentId = 0)
  180. {
  181. if (empty(static::$branchOrder)) {
  182. static::setBranchOrder($tree);
  183. }
  184. foreach ($tree as $branch) {
  185. $node = static::find($branch['id']);
  186. $node->{$node->getParentColumn()} = $parentId;
  187. $node->{$node->getOrderColumn()} = static::$branchOrder[$branch['id']];
  188. $node->save();
  189. if (isset($branch['children'])) {
  190. static::saveOrder($branch['children'], $branch['id']);
  191. }
  192. }
  193. }
  194. /**
  195. * Get options for Select field in form.
  196. *
  197. * @param \Closure|null $closure
  198. * @param string $rootText
  199. *
  200. * @return array
  201. */
  202. public static function selectOptions(\Closure $closure = null, $rootText = 'Root')
  203. {
  204. $options = (new static())->withQuery($closure)->buildSelectOptions();
  205. return collect($options)->prepend($rootText, 0)->all();
  206. }
  207. /**
  208. * Build options of select field in form.
  209. *
  210. * @param array $nodes
  211. * @param int $parentId
  212. * @param string $prefix
  213. *
  214. * @return array
  215. */
  216. protected function buildSelectOptions(array $nodes = [], $parentId = 0, $prefix = '')
  217. {
  218. $prefix = $prefix ?: str_repeat('&nbsp;', 6);
  219. $options = [];
  220. if (empty($nodes)) {
  221. $nodes = $this->allNodes();
  222. }
  223. foreach ($nodes as $node) {
  224. $node[$this->titleColumn] = $prefix.'&nbsp;'.$node[$this->titleColumn];
  225. if ($node[$this->parentColumn] == $parentId) {
  226. $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $prefix.$prefix);
  227. $options[$node[$this->getKeyName()]] = $node[$this->titleColumn];
  228. if ($children) {
  229. $options += $children;
  230. }
  231. }
  232. }
  233. return $options;
  234. }
  235. /**
  236. * {@inheritdoc}
  237. */
  238. public function delete()
  239. {
  240. $this->where($this->parentColumn, $this->getKey())->delete();
  241. return parent::delete();
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. protected static function boot()
  247. {
  248. parent::boot();
  249. static::saving(function (Model $branch) {
  250. $parentColumn = $branch->getParentColumn();
  251. if (Request::has($parentColumn) && Request::input($parentColumn) == $branch->getKey()) {
  252. throw new \Exception(trans('admin.parent_select_error'));
  253. }
  254. if (Request::has('_order')) {
  255. $order = Request::input('_order');
  256. Request::offsetUnset('_order');
  257. static::tree()->saveOrder($order);
  258. return false;
  259. }
  260. return $branch;
  261. });
  262. }
  263. }