Skip to content

Commit

Permalink
[6.x] Add existsOr and doesntExistOr to the querybuilder (#30495)
Browse files Browse the repository at this point in the history
* add existsOr and doesntExistOr to the querybuilder

* ci
  • Loading branch information
SjorsO authored and taylorotwell committed Nov 5, 2019
1 parent 726f0e1 commit 3f60972
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2406,6 +2406,28 @@ public function doesntExist()
return ! $this->exists();
}

/**
* Execute the given callback if no rows exist for the current query.
*
* @param \Closure $callback
* @return mixed
*/
public function existsOr(Closure $callback)
{
return $this->exists() ? true : $callback();
}

/**
* Execute the given callback if rows exist for the current query.
*
* @param \Closure $callback
* @return mixed
*/
public function doesntExistOr(Closure $callback)
{
return $this->doesntExist() ? true : $callback();
}

/**
* Retrieve the "count" result of the query.
*
Expand Down
32 changes: 32 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1825,6 +1825,38 @@ public function testSqlServerExists()
$this->assertTrue($results);
}

public function testExistsOr()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->andReturn([['exists' => 1]]);
$results = $builder->from('users')->doesntExistOr(function () {
return 123;
});
$this->assertSame(123, $results);
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->andReturn([['exists' => 0]]);
$results = $builder->from('users')->doesntExistOr(function () {
throw new RuntimeException();
});
$this->assertTrue($results);
}

public function testDoesntExistsOr()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->andReturn([['exists' => 0]]);
$results = $builder->from('users')->existsOr(function () {
return 123;
});
$this->assertSame(123, $results);
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->andReturn([['exists' => 1]]);
$results = $builder->from('users')->existsOr(function () {
throw new RuntimeException();
});
$this->assertTrue($results);
}

public function testAggregateResetFollowedByGet()
{
$builder = $this->getBuilder();
Expand Down

0 comments on commit 3f60972

Please sign in to comment.