Skip to content

Commit

Permalink
Merge pull request #3157 from JurianArie/patch-3
Browse files Browse the repository at this point in the history
fix: make query for filteredRecords when totalRecords was manually set
  • Loading branch information
yajra authored Jul 15, 2024
2 parents 393296d + 4d69cdd commit 337685d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
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
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

0 comments on commit 337685d

Please sign in to comment.