Skip to content

Commit ef72559

Browse files
committed
Allow count with WHERE clause
1 parent 6db8dea commit ef72559

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/Model.php

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use Exception;
1616
use Framework\Cache\Cache;
1717
use Framework\Database\Database;
18+
use Framework\Database\Manipulation\Traits\Where;
1819
use Framework\Language\Language;
1920
use Framework\Pagination\Pager;
2021
use Framework\Validation\Debug\ValidationCollector;
@@ -401,23 +402,28 @@ protected function getDatabaseToWrite() : Database
401402
}
402403

403404
/**
404-
* A basic function to count all rows in the table.
405+
* A basic function to count rows in the table.
406+
*
407+
* @param array<array<mixed>> $where Array in this format: `[['id', '=', 25]]`
408+
*
409+
* @see Where
405410
*
406411
* @return int
407412
*/
408-
public function count() : int
413+
public function count(array $where = []) : int
409414
{
410-
$result = $this->getDatabaseToRead()
415+
$select = $this->getDatabaseToRead()
411416
->select()
412417
->expressions([
413418
'count' => static function () : string {
414419
return 'COUNT(*)';
415420
},
416421
])
417-
->from($this->getTable())
418-
->run()
419-
->fetch();
420-
return $result->count; // @phpstan-ignore-line
422+
->from($this->getTable());
423+
foreach ($where as $args) {
424+
$select->where(...$args);
425+
}
426+
return $select->run()->fetch()->count; // @phpstan-ignore-line
421427
}
422428

423429
/**

tests/ModelTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,13 @@ public function testDeleteByWithCall() : void
397397
public function testCount() : void
398398
{
399399
self::assertSame(2, $this->model->count());
400+
self::assertSame(1, $this->model->count([
401+
['id', '=', 1],
402+
]));
403+
self::assertSame(2, $this->model->count([
404+
['id', 'is not null'],
405+
['id', '<', 3],
406+
]));
400407
}
401408

402409
public function testPaginatedItems() : void

0 commit comments

Comments
 (0)