Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/QueryDataTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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();
Expand Down
11 changes: 9 additions & 2 deletions tests/Integration/QueryDataTableTest.php
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes from c37494f to the tests have been reverted, the optimalization should not have changed this behavior.

Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function it_can_set_total_records()
$crawler->assertJson([
'draw' => 0,
'recordsTotal' => 10,
'recordsFiltered' => 10,
'recordsFiltered' => 20,
]);
}

Expand All @@ -37,7 +37,7 @@ public function it_can_set_zero_total_records()
$crawler->assertJson([
'draw' => 0,
'recordsTotal' => 0,
'recordsFiltered' => 0,
'recordsFiltered' => 20,
]);
}

Expand All @@ -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]
Expand Down