@@ -860,6 +860,75 @@ public function testWhereIsLeaf()
860
860
861
861
$ this ->assertFalse ($ category ->isLeaf ());
862
862
}
863
+
864
+ public function testEagerLoadAncestors ()
865
+ {
866
+ $ queryLogCount = count (Capsule::connection ()->getQueryLog ());
867
+ $ categories = Category::with ('ancestors ' )->orderBy ('name ' )->get ();
868
+
869
+ $ this ->assertEquals ($ queryLogCount + 2 , count (Capsule::connection ()->getQueryLog ()));
870
+
871
+ $ expectedShape = [
872
+ 'apple (3)} ' => 'store (1) > notebooks (2) ' ,
873
+ 'galaxy (8)} ' => 'store (1) > mobile (5) > samsung (7) ' ,
874
+ 'lenovo (4)} ' => 'store (1) > notebooks (2) ' ,
875
+ 'lenovo (10)} ' => 'store (1) > mobile (5) ' ,
876
+ 'mobile (5)} ' => 'store (1) ' ,
877
+ 'nokia (6)} ' => 'store (1) > mobile (5) ' ,
878
+ 'notebooks (2)} ' => 'store (1) ' ,
879
+ 'samsung (7)} ' => 'store (1) > mobile (5) ' ,
880
+ 'sony (9)} ' => 'store (1) > mobile (5) ' ,
881
+ 'store (1)} ' => '' ,
882
+ 'store_2 (11)} ' => ''
883
+ ];
884
+
885
+ $ output = [];
886
+
887
+ foreach ($ categories as $ category ) {
888
+ $ output ["{$ category ->name } ( {$ category ->id })} " ] = $ category ->ancestors ->count ()
889
+ ? implode (' > ' , $ category ->ancestors ->map (function ($ cat ) { return "{$ cat ->name } ( {$ cat ->id }) " ; })->toArray ())
890
+ : '' ;
891
+ }
892
+
893
+ $ this ->assertEquals ($ expectedShape , $ output );
894
+ }
895
+
896
+ public function testLazyLoadAncestors ()
897
+ {
898
+ $ queryLogCount = count (Capsule::connection ()->getQueryLog ());
899
+ $ categories = Category::orderBy ('name ' )->get ();
900
+
901
+ $ this ->assertEquals ($ queryLogCount + 1 , count (Capsule::connection ()->getQueryLog ()));
902
+
903
+ $ expectedShape = [
904
+ 'apple (3)} ' => 'store (1) > notebooks (2) ' ,
905
+ 'galaxy (8)} ' => 'store (1) > mobile (5) > samsung (7) ' ,
906
+ 'lenovo (4)} ' => 'store (1) > notebooks (2) ' ,
907
+ 'lenovo (10)} ' => 'store (1) > mobile (5) ' ,
908
+ 'mobile (5)} ' => 'store (1) ' ,
909
+ 'nokia (6)} ' => 'store (1) > mobile (5) ' ,
910
+ 'notebooks (2)} ' => 'store (1) ' ,
911
+ 'samsung (7)} ' => 'store (1) > mobile (5) ' ,
912
+ 'sony (9)} ' => 'store (1) > mobile (5) ' ,
913
+ 'store (1)} ' => '' ,
914
+ 'store_2 (11)} ' => ''
915
+ ];
916
+
917
+ $ output = [];
918
+
919
+ foreach ($ categories as $ category ) {
920
+ $ output ["{$ category ->name } ( {$ category ->id })} " ] = $ category ->ancestors ->count ()
921
+ ? implode (' > ' , $ category ->ancestors ->map (function ($ cat ) { return "{$ cat ->name } ( {$ cat ->id }) " ; })->toArray ())
922
+ : '' ;
923
+ }
924
+
925
+ // assert that there is number of original query + 1 + number of rows to fulfill the relation
926
+ $ this ->assertEquals ($ queryLogCount + 12 , count (Capsule::connection ()->getQueryLog ()));
927
+
928
+ $ this ->assertEquals ($ expectedShape , $ output );
929
+ }
930
+
931
+
863
932
}
864
933
865
934
function all ($ items )
0 commit comments