1919use Quantum \Paginator \Contracts \PaginatorInterface ;
2020use Quantum \Paginator \Traits \PaginatorTrait ;
2121use Quantum \App \Exceptions \BaseException ;
22+ use Quantum \Model \Exceptions \ModelException ;
2223use Quantum \Di \Exceptions \DiException ;
2324use Quantum \Model \ModelCollection ;
2425use Quantum \Model \DbModel ;
@@ -38,15 +39,15 @@ class ModelPaginator implements PaginatorInterface
3839 private DbModel $ model ;
3940
4041 /**
41- * @throws DiException|ReflectionException
42+ * @throws DiException|ReflectionException|ModelException|BaseException
4243 */
4344 public function __construct (DbModel $ model , int $ perPage , int $ page = 1 )
4445 {
4546 $ this ->initialize ($ perPage , $ page );
4647
4748 $ this ->model = $ model ;
4849 $ this ->modelClass = $ model ->getModelName ();
49- $ this ->total = $ model -> count ( );
50+ $ this ->total = $ this -> getCountFromClonedModel ( $ model );
5051 }
5152
5253 /**
@@ -99,4 +100,17 @@ public function lastItem(): ?Model
99100
100101 return $ data ->last ();
101102 }
103+
104+ /**
105+ * Counts results on an isolated model/ORM clone so total calculation cannot mutate
106+ * the live model query state later used by paginator data().
107+ * @throws ModelException|BaseException
108+ */
109+ private function getCountFromClonedModel (DbModel $ model ): int
110+ {
111+ $ countModel = clone $ model ;
112+ $ countModel ->setOrmInstance (clone $ model ->getOrmInstance ());
113+
114+ return $ countModel ->count ();
115+ }
102116}
0 commit comments