Skip to content

Commit

Permalink
Adding whereNotNull() and whereNull() to the query object
Browse files Browse the repository at this point in the history
  • Loading branch information
burzum committed Apr 3, 2018
1 parent 98ba1cf commit 60c0b63
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 1 deletion.
44 changes: 44 additions & 0 deletions src/Database/Query.php
Expand Up @@ -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.
Expand Down
46 changes: 45 additions & 1 deletion tests/TestCase/Database/QueryTest.php
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 60c0b63

Please sign in to comment.