Skip to content

Commit 337685d

Browse files
authored
Merge pull request #3157 from JurianArie/patch-3
fix: make query for filteredRecords when totalRecords was manually set
2 parents 393296d + 4d69cdd commit 337685d

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/QueryDataTable.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ class QueryDataTable extends DataTableAbstract
2525
*/
2626
protected bool $prepared = false;
2727

28+
/**
29+
* Flag to check if the total records count query has been performed.
30+
*/
31+
protected bool $performedTotalRecordsCount = false;
32+
2833
/**
2934
* Query callback for custom pagination using limit without offset.
3035
*
@@ -157,6 +162,20 @@ public function prepareQuery(): static
157162
return $this;
158163
}
159164

165+
/**
166+
* Count total items.
167+
*/
168+
public function totalCount(): int
169+
{
170+
if ($this->totalRecords !== null) {
171+
return $this->totalRecords;
172+
}
173+
174+
$this->performedTotalRecordsCount = true;
175+
176+
return $this->totalRecords = $this->count();
177+
}
178+
160179
/**
161180
* Counts current query.
162181
*/
@@ -253,7 +272,7 @@ protected function filterRecords(): void
253272

254273
// If no modification between the original query and the filtered one has been made
255274
// the filteredRecords equals the totalRecords
256-
if ($this->query == $initialQuery) {
275+
if ($this->query == $initialQuery && $this->performedTotalRecordsCount) {
257276
$this->filteredRecords ??= $this->totalRecords;
258277
} else {
259278
$this->filteredCount();

tests/Integration/QueryDataTableTest.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function it_can_set_total_records()
2626
$crawler->assertJson([
2727
'draw' => 0,
2828
'recordsTotal' => 10,
29-
'recordsFiltered' => 10,
29+
'recordsFiltered' => 20,
3030
]);
3131
}
3232

@@ -37,7 +37,7 @@ public function it_can_set_zero_total_records()
3737
$crawler->assertJson([
3838
'draw' => 0,
3939
'recordsTotal' => 0,
40-
'recordsFiltered' => 0,
40+
'recordsFiltered' => 20,
4141
]);
4242
}
4343

@@ -55,12 +55,19 @@ public function it_can_set_total_filtered_records()
5555
#[Test]
5656
public function it_returns_all_records_when_no_parameters_is_passed()
5757
{
58+
DB::enableQueryLog();
59+
5860
$crawler = $this->call('GET', '/query/users');
5961
$crawler->assertJson([
6062
'draw' => 0,
6163
'recordsTotal' => 20,
6264
'recordsFiltered' => 20,
6365
]);
66+
67+
DB::disableQueryLog();
68+
$queryLog = DB::getQueryLog();
69+
70+
$this->assertCount(2, $queryLog);
6471
}
6572

6673
#[Test]

0 commit comments

Comments
 (0)