From 95c6059aa1767b8bca1df716903adf684cacdbf8 Mon Sep 17 00:00:00 2001 From: JaguarJack Date: Tue, 25 May 2021 08:28:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=20tree=20=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E5=88=87=E6=8D=A2=20pk=20=E4=B8=BB=E9=94=AE=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extend/catcher/CatchModelCollection.php | 8 ++++++- extend/catcher/Tree.php | 32 ++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/extend/catcher/CatchModelCollection.php b/extend/catcher/CatchModelCollection.php index e62f85e..0c9b627 100644 --- a/extend/catcher/CatchModelCollection.php +++ b/extend/catcher/CatchModelCollection.php @@ -22,7 +22,13 @@ class CatchModelCollection extends Collection */ public function toTree($pid = 0, $pidField = 'parent_id', $children = 'children'): array { - return Tree::done($this->toArray(), $pid, $pidField, $children); + $pk = 'id'; + + if ($this->count()) { + $pk = $this->first()->getPk(); + } + + return Tree::setPk($pk)->done($this->toArray(), $pid, $pidField, $children); } diff --git a/extend/catcher/Tree.php b/extend/catcher/Tree.php index 39bff67..b19bdd8 100644 --- a/extend/catcher/Tree.php +++ b/extend/catcher/Tree.php @@ -5,13 +5,25 @@ namespace catcher; class Tree { - public static function done(array $items, $pid = 0, $pidField = 'parent_id', $children = 'children') + protected static $pk = 'id'; + + /** + * + * @author CatchAdmin + * @time 2021年05月25日 + * @param array $items + * @param int $pid + * @param string $pidField + * @param string $children + * @return array + */ + public static function done(array $items, $pid = 0, $pidField = 'parent_id', $children = 'children'): array { $tree = []; - foreach ($items as $key => $item) { + foreach ($items as $item) { if ($item[$pidField] == $pid) { - $child = self::done($items, $item['id'], $pidField); + $child = self::done($items, $item[self::$pk], $pidField); if (count($child)) { $item[$children] = $child; } @@ -22,5 +34,19 @@ class Tree return $tree; } + /** + * set pk field + * + * @author CatchAdmin + * @time 2021年05月25日 + * @param string $pk + * @return $this + */ + public static function setPk(string $pk): Tree + { + self::$pk = $pk; + + return new self; + } }