diff --git a/src/Datatables.php b/src/Datatables.php index d77028e..e9d70e2 100644 --- a/src/Datatables.php +++ b/src/Datatables.php @@ -55,6 +55,16 @@ class Datatables */ protected $distinctData = []; + /** + * @var array + */ + private $queries = []; + + /** + * @var int + */ + private $recordsTotal; + /** * Datatables constructor. * @@ -234,21 +244,37 @@ private function getDistinctData(): array return $output ?? []; } + public function setTotalRecords(int $total): Datatables + { + $this->recordsTotal = $total; + + return $this; + } + /** * */ public function setResponseData(): void { + $this->queries = []; $this->response['draw'] = $this->options->draw(); - $this->response['recordsTotal'] = $this->db->count($this->builder->query); + + if (is_null($this->recordsTotal)) { + $this->response['recordsTotal'] = $this->db->count($this->builder->query); + $this->queries['query'] = $this->builder->query; + } else { + $this->response['recordsTotal'] = $this->recordsTotal; + } if($this->builder->query->sql === $this->builder->filtered->sql) { $this->response['recordsFiltered'] = $this->response['recordsTotal']; } else { $this->response['recordsFiltered'] = $this->db->count($this->builder->filtered); + $this->queries['recordsFiltered'] = $this->builder->filtered; } $this->response['data'] = $this->getData(); + $this->queries['full'] = $this->builder->full; if (\count($this->distinctColumn) > 0 || \count($this->distinctData) > 0) { $this->response['distinctData'] = array_merge($this->response['distinctData'] ?? [], @@ -256,6 +282,14 @@ public function setResponseData(): void } } + /** + * @return array + */ + public function queries(): array + { + return $this->queries; + } + /** * @return string */ diff --git a/tests/unit/DatatablesTest.php b/tests/unit/DatatablesTest.php index dbdbf8d..47c5182 100644 --- a/tests/unit/DatatablesTest.php +++ b/tests/unit/DatatablesTest.php @@ -45,6 +45,24 @@ public function testReturnsRecordCounts() $this->assertSame(8, $datatables['recordsFiltered']); } + public function testReturnsRecordCountsThatSetWithoutRunningAnotherQuery() + { + $this->db->query('select id as fid, name, surname, age from mytable where id > 3'); + + $datatables = $this->db->generate()->toArray(); + + $this->assertSame(2, count($this->db->queries())); + $this->assertSame(8, $datatables['recordsTotal']); + $this->assertSame(8, $datatables['recordsFiltered']); + + $this->db->setTotalRecords(8); + $datatables = $this->db->generate()->toArray(); + + $this->assertSame(1, count($this->db->queries())); + $this->assertSame(8, $datatables['recordsTotal']); + $this->assertSame(8, $datatables['recordsFiltered']); + } + public function testReturnsDataFromABasicSql() { $this->db->query('select id as fid, name, surname, age from mytable'); @@ -155,7 +173,6 @@ public function testFiltersDataViaGlobalSearch() $this->assertSame(11, $datatables['recordsTotal']); $this->assertSame(2, $datatables['recordsFiltered']); - } public function testSortsDataViaSorting()