@@ -72,6 +72,8 @@ class SelectTree extends Field implements HasAffixActions
7272
7373 protected ?Closure $ modifyChildQueryUsing = null ;
7474
75+ protected Closure |bool $ strictNullParentRootNodes = false ;
76+
7577 protected Closure |int $ defaultOpenLevel = 0 ;
7678
7779 protected string $ direction = 'auto ' ;
@@ -246,8 +248,11 @@ private function buildTreeFromResults($results, $parent = null): Collection
246248 }
247249 }
248250
249- // Filter the cache for missing parents in the result set and get the children
250- $ orphanedResults = array_map (
251+ // If the tree has strict rull parent root nodes, only retrieve children whose parent is the null value
252+ // Otherwise, promote other orphaned children to root nodes
253+ $ orphanedResults = $ this ->hasStrictNullParentRootNodes ()
254+ ? [$ parent => $ resultCache [$ parent ]['children ' ]]
255+ : array_map (
251256 fn ($ item ) => $ item ['children ' ],
252257 array_filter (
253258 $ resultCache ,
@@ -256,6 +261,7 @@ private function buildTreeFromResults($results, $parent = null): Collection
256261 );
257262
258263 // Move any remaining children from the cache into the root of the tree, since their parents do not show up in the result set
264+
259265 $ resultMap [$ parent ] = [];
260266 foreach ($ orphanedResults as $ orphanedResult ) {
261267 $ resultMap [$ parent ] += $ orphanedResult ;
@@ -333,6 +339,13 @@ public function query(Builder|Closure|null $query, string $titleAttribute, strin
333339 return $ this ;
334340 }
335341
342+ public function strictNullParentRootNodes (Closure |bool $ condition = true ): static
343+ {
344+ $ this ->strictNullParentRootNodes = $ condition ;
345+
346+ return $ this ;
347+ }
348+
336349 public function withCount (bool $ withCount = true ): static
337350 {
338351 $ this ->withCount = $ withCount ;
@@ -400,6 +413,11 @@ public function getQuery(): ?Builder
400413 return $ this ->getRelationship ()->getRelated ()->query ();
401414 }
402415
416+ public function hasStrictNullParentRootNodes (): bool
417+ {
418+ return $ this ->evaluate ($ this ->strictNullParentRootNodes );
419+ }
420+
403421 public function getTitleAttribute (): string
404422 {
405423 return $ this ->evaluate ($ this ->titleAttribute );
0 commit comments