diff --git a/src/QueryDataTable.php b/src/QueryDataTable.php index b6bc0813..aea42844 100644 --- a/src/QueryDataTable.php +++ b/src/QueryDataTable.php @@ -25,6 +25,11 @@ class QueryDataTable extends DataTableAbstract */ protected bool $prepared = false; + /** + * Flag to check if the total records count query has been performed. + */ + protected bool $performedTotalRecordsCount = false; + /** * Query callback for custom pagination using limit without offset. * @@ -157,6 +162,20 @@ public function prepareQuery(): static return $this; } + /** + * Count total items. + */ + public function totalCount(): int + { + if ($this->totalRecords !== null) { + return $this->totalRecords; + } + + $this->performedTotalRecordsCount = true; + + return $this->totalRecords = $this->count(); + } + /** * Counts current query. */ @@ -253,7 +272,7 @@ protected function filterRecords(): void // If no modification between the original query and the filtered one has been made // the filteredRecords equals the totalRecords - if ($this->query == $initialQuery) { + if ($this->query == $initialQuery && $this->performedTotalRecordsCount) { $this->filteredRecords ??= $this->totalRecords; } else { $this->filteredCount(); diff --git a/tests/Integration/QueryDataTableTest.php b/tests/Integration/QueryDataTableTest.php index 5c8d9399..d2b4a028 100644 --- a/tests/Integration/QueryDataTableTest.php +++ b/tests/Integration/QueryDataTableTest.php @@ -26,7 +26,7 @@ public function it_can_set_total_records() $crawler->assertJson([ 'draw' => 0, 'recordsTotal' => 10, - 'recordsFiltered' => 10, + 'recordsFiltered' => 20, ]); } @@ -37,7 +37,7 @@ public function it_can_set_zero_total_records() $crawler->assertJson([ 'draw' => 0, 'recordsTotal' => 0, - 'recordsFiltered' => 0, + 'recordsFiltered' => 20, ]); } @@ -55,12 +55,19 @@ public function it_can_set_total_filtered_records() #[Test] public function it_returns_all_records_when_no_parameters_is_passed() { + DB::enableQueryLog(); + $crawler = $this->call('GET', '/query/users'); $crawler->assertJson([ 'draw' => 0, 'recordsTotal' => 20, 'recordsFiltered' => 20, ]); + + DB::disableQueryLog(); + $queryLog = DB::getQueryLog(); + + $this->assertCount(2, $queryLog); } #[Test]