diff --git a/src/Extensions/Collection.php b/src/Extensions/Collection.php index 66adff1..05237df 100644 --- a/src/Extensions/Collection.php +++ b/src/Extensions/Collection.php @@ -171,8 +171,10 @@ protected function makeTree(array $items) $parentId = $item->parent_id; if (array_key_exists($parentId, $result)) { + $item->isParent = false; $result[$parentId]->appendChild($item); } else { + $item->isParent = true; $tops[] = $item; } } diff --git a/src/Models/Entity.php b/src/Models/Entity.php index df423c6..e0b8d05 100644 --- a/src/Models/Entity.php +++ b/src/Models/Entity.php @@ -354,6 +354,38 @@ public function getParent(array $columns = ['*']) return $this->exists ? $this->find($this->parent_id, $columns) : null; } + protected function joinClosureByTrashed($column, $withSelf = false) + { + $primary = $this->getQualifiedKeyName(); + $closure = $this->closure->getTable(); + $ancestor = $this->closure->getQualifiedAncestorColumn(); + $descendant = $this->closure->getQualifiedDescendantColumn(); + + switch ($column) { + case 'ancestor': + $query = $this->join($closure, $ancestor, '=', $primary) + ->where($descendant, '=', $this->getKey()); + break; + + case 'descendant': + $query = $this->join($closure, $descendant, '=', $primary) + ->where($ancestor, '=', $this->getKey()); + break; + } + + $depthOperator = ($withSelf === true ? '>=' : '>'); + + $query->withTrashed()->where($this->closure->getQualifiedDepthColumn(), $depthOperator, 0); + + return $query; + } + + public function restoreTree($withSelf) + { + $ids = $this->joinClosureByTrashed('descendant', $withSelf)->pluck($this->getQualifiedKeyName()); + return $this->whereIn($this->getKeyName(), $ids)->restore(); + } + /** * Returns query builder for ancestors. * @@ -1697,6 +1729,30 @@ public static function getTree(array $columns = ['*']) ->toTree(); } + /** + * Retrieves entire tree with trashed + * + * @param array $columns + * + * @return Collection + * @deprecated since 6.0 + */ + public static function getTreeWithTrashed(array $columns = ['*']) + { + /** + * @var Entity $instance + */ + $instance = new static; + + return $instance + ->withTrashed() + ->load(static::CHILDREN_RELATION_NAME) + ->orderBy($instance->getParentIdColumn()) + ->orderBy($instance->getPositionColumn()) + ->get($instance->prepareTreeQueryColumns($columns)) + ->toTree(); + } + /** * Retrieves tree by condition. * @@ -1813,7 +1869,7 @@ public static function getLatestPosition(Entity $entity) $positionColumn = $entity->getPositionColumn(); $parentIdColumn = $entity->getParentIdColumn(); - $latest = $entity->select($positionColumn) + $latest = $entity->withTrashed()->select($positionColumn) ->where($parentIdColumn, '=', $entity->parent_id) ->latest($positionColumn) ->first();