@@ -142,6 +142,13 @@ class Model {
142142 */
143143 public Cache |null $ cache = null ;
144144
145+ /**
146+ * @var array $object_cache
147+ * An array used internally to cache already loaded ModelSets for any Model class. This prevents redundant loading
148+ * of ModelSet objects during operations that may require multiple references to the same ModelSet.
149+ */
150+ public static array $ object_cache = [];
151+
145152 /**
146153 * @var ModelSet $related_objects
147154 * A ModelSet containing foreign Model objects related to this Model. These are primarily populated by
@@ -1882,6 +1889,7 @@ class Model {
18821889 $ model_objects = [];
18831890 $ is_parent_model_many = $ model ->is_parent_model_many ();
18841891 $ requests_pagination = ($ limit or $ offset );
1892+ $ cache_exempt = ($ requests_pagination or $ reverse );
18851893
18861894 # Throw an error if this Model has a $many parent Model, but no parent Model ID was given
18871895 if ($ is_parent_model_many and !isset ($ parent_id )) {
@@ -1900,6 +1908,11 @@ class Model {
19001908 );
19011909 }
19021910
1911+ # Load from cache if it is not exempt and cached objects exist
1912+ if (!$ cache_exempt and Model::$ object_cache [$ model_name ]) {
1913+ return Model::$ object_cache [$ model_name ];
1914+ }
1915+
19031916 # Obtain all of this Model's internally stored objects
19041917 $ internal_objects = $ model ->get_internal_objects ();
19051918
@@ -1926,8 +1939,16 @@ class Model {
19261939 $ model_objects [] = $ model_object ;
19271940 }
19281941
1942+ # Load the ModelSet with all obtained Model objects
1943+ $ modelset = new ModelSet (model_objects: $ model_objects );
1944+
1945+ # For many models, cache the ModelSet if not exempt
1946+ if ($ model ->many and !$ cache_exempt ) {
1947+ Model::$ object_cache [$ model_name ] = new ModelSet (model_objects: $ model_objects );
1948+ }
1949+
19291950 # For many enabled Models return a ModelSet, otherwise return a single Model object
1930- return $ model ->many ? new ModelSet (model_objects: $ model_objects ) : $ model_objects [ 0 ] ;
1951+ return $ model ->many ? $ modelset : $ modelset -> first () ;
19311952 }
19321953
19331954 /**
0 commit comments