支持 tree 动态切换 pk 主键名称
This commit is contained in:
parent
3bad548d10
commit
95c6059aa1
@ -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);
|
||||
}
|
||||
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user