diff --git a/src/Database/Query.php b/src/Database/Query.php index 231b0f748fb..ab8bf16e19a 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -881,6 +881,50 @@ public function where($conditions = null, $types = [], $overwrite = false) return $this; } + /** + * Convenience method that adds a NOT NULL condition to the query + * + * @param array $fields A list of fields that should be not null + * @param bool $isNull Toggles between NOT NULL and NULL checks + * @return $this + */ + protected function whereNullOrNotNull($fields, $isNull = true) + { + foreach ($fields as $condition) { + $this->where(function ($exp) use ($condition, $isNull) { + if ($isNull) { + return $exp->isNull($condition); + } else { + return $exp->isNotNull($condition); + } + }); + } + + return $this; + } + + /** + * Convenience method that adds a NOT NULL condition to the query + * + * @param array $fields A list of fields that should be not null + * @return $this + */ + public function whereNotNull($fields) + { + return $this->whereNullOrNotNull($fields, false); + } + + /** + * Convenience method that adds a IS NULL condition to the query + * + * @param array $fields A list of fields that should be not null + * @return $this + */ + public function whereNull($fields) + { + return $this->whereNullOrNotNull($fields, true); + } + /** * Adds an IN condition or set of conditions to be used in the WHERE clause for this * query. diff --git a/tests/TestCase/Database/QueryTest.php b/tests/TestCase/Database/QueryTest.php index b988097ebee..b73a60c6302 100644 --- a/tests/TestCase/Database/QueryTest.php +++ b/tests/TestCase/Database/QueryTest.php @@ -28,7 +28,13 @@ class QueryTest extends TestCase { - public $fixtures = ['core.articles', 'core.authors', 'core.comments', 'core.profiles']; + public $fixtures = [ + 'core.articles', + 'core.authors', + 'core.comments', + 'core.profiles', + 'core.menu_link_trees' + ]; public $autoFixtures = false; @@ -742,6 +748,44 @@ public function testSelectWhereTypes() $result->closeCursor(); } + /** + * Tests Query::whereNull() + * + * @return void + */ + public function testSelectWhereNull() + { + $this->loadFixtures('MenuLinkTrees'); + + $query = new Query($this->connection); + $result = $query + ->select(['id', 'parent_id']) + ->from('menu_link_trees') + ->whereNull(['parent_id']) + ->execute(); + $this->assertCount(5, $result); + $result->closeCursor(); + } + + /** + * Tests Query::whereNotNull() + * + * @return void + */ + public function testSelectWhereNotNull() + { + $this->loadFixtures('MenuLinkTrees'); + + $query = new Query($this->connection); + $result = $query + ->select(['id', 'parent_id']) + ->from('menu_link_trees') + ->whereNotNull(['parent_id']) + ->execute(); + $this->assertCount(13, $result); + $result->closeCursor(); + } + /** * Tests that passing an array type to any where condition will replace * the passed array accordingly as a proper IN condition