Skip to content

[5.7] Query builder - dynamic "where" clauses #249

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,54 @@ public function orWhereNotNull($column)
return $this->whereNotNull($column, 'or');
}

/**
* Handles dynamic "where" clauses to the query.
*
* @param string $method
* @param string $parameters
*/
public function dynamicWhere($method, $parameters)
{
$finder = substr($method, 5);

$flags = PREG_SPLIT_DELIM_CAPTURE;

$segments = preg_split('/(And|Or)(?=[A-Z])/', $finder, -1, $flags);

// The connector variable will determine which connector will be used
// for the condition. We'll change it as we come across new boolean
// connectors in the dynamic method string.
$connector = 'and';

// The index variable helps us get the correct parameter value for
// the where condition. We increment it each time we add another
// condition to the query's where clause.
$index = 0;

foreach ($segments as $segment)
{
// If the segment is not a boolean connector, we can assume it it is
// a column name, and we'll add it to the query as a new constraint
// of the query's where clause and keep iterating the segments.
if ($segment != 'And' and $segment != 'Or')
{
$this->where(snake_case($segment), '=', $parameters[$index], strtolower($connector));

$index++;
}

// Otherwise, we will store the connector so we know how the next
// where clause we find in the query should be connected to the
// previous one and will add it when we find the next one.
else
{
$connector = $segment;
}
}

return $this;
}

/**
* Add a "group by" clause to the query.
*
Expand Down Expand Up @@ -1282,4 +1330,22 @@ public function getGrammar()
return $this->grammar;
}

}
/**
* Handle dynamic method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (starts_with($method, 'where'))
{
return $this->dynamicWhere($method, $parameters);
}

$className = get_class($this);
throw new \BadMethodCallException("Call to undefined method {$className}::{$method}()");
}

}
60 changes: 54 additions & 6 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ public function testRawWheres()
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereRaw('id = ? or email = ?', array(1, 'foo'));
$this->assertEquals('select * from "users" where id = ? or email = ?', $builder->toSql());
$this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings());
$this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings());
}

public function testRawOrWheres()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('id', '=', 1)->orWhereRaw('email = ?', array('foo'));
$this->assertEquals('select * from "users" where "id" = ? or email = ?', $builder->toSql());
$this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings());
$this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings());
}


Expand Down Expand Up @@ -194,7 +194,7 @@ public function testHavings()
$builder = $this->getBuilder();
$builder->select('*')->from('users')->having('email', '>', 1);
$this->assertEquals('select * from "users" having "email" > ?', $builder->toSql());

$builder = $this->getBuilder();
$builder->select('*')->from('users')->groupBy('email')->having('email', '>', 1);
$this->assertEquals('select * from "users" group by "email" having "email" > ?', $builder->toSql());
Expand Down Expand Up @@ -338,7 +338,7 @@ public function testFirstMethodReturnsFirstResult()
$builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar')));
$builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, array(array('foo' => 'bar')));
$results = $builder->from('users')->where('id', '=', 1)->first();
$this->assertEquals(array('foo' => 'bar'), $results);
$this->assertEquals(array('foo' => 'bar'), $results);
}


Expand All @@ -354,7 +354,7 @@ public function testListMethodsGetsArrayOfColumnValues()
$builder->getConnection()->shouldReceive('select')->once()->andReturn(array(array('id' => 1, 'foo' => 'bar'), array('id' => 10, 'foo' => 'baz')));
$builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, array(array('id' => 1, 'foo' => 'bar'), array('id' => 10, 'foo' => 'baz')));
$results = $builder->from('users')->where('id', '=', 1)->lists('foo', 'id');
$this->assertEquals(array(1 => 'bar', 10 => 'baz'), $results);
$this->assertEquals(array(1 => 'bar', 10 => 'baz'), $results);
}


Expand Down Expand Up @@ -417,7 +417,7 @@ public function testPluckMethodReturnsSingleColumn()
$builder->getConnection()->shouldReceive('select')->once()->with('select "foo" from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar')));
$builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, array(array('foo' => 'bar')));
$results = $builder->from('users')->where('id', '=', 1)->pluck('foo');
$this->assertEquals('bar', $results);
$this->assertEquals('bar', $results);
}


Expand Down Expand Up @@ -611,6 +611,54 @@ public function testProvidingNullOrFalseAsSecondParameterBuildsCorrectly()
}


public function testDynamicWhere()
{
$method = 'whereFooBarAndBazOrQux';
$parameters = array('corge', 'waldo', 'fred');
$builder = m::mock('Illuminate\Database\Query\Builder[where]');

$builder->shouldReceive('where')->with('foo_bar', '=', $parameters[0], 'and')->once()->andReturn($builder);
$builder->shouldReceive('where')->with('baz', '=', $parameters[1], 'and')->once()->andReturn($builder);
$builder->shouldReceive('where')->with('qux', '=', $parameters[2], 'or')->once()->andReturn($builder);

$this->assertEquals($builder, $builder->dynamicWhere($method, $parameters));
}


public function testDynamicWhereIsNotGreedy()
{
$method = 'whereIosVersionAndAndroidVersionOrOrientation';
$parameters = array('6.1', '4.2', 'Vertical');
$builder = m::mock('Illuminate\Database\Query\Builder[where]');

$builder->shouldReceive('where')->with('ios_version', '=', '6.1', 'and')->once()->andReturn($builder);
$builder->shouldReceive('where')->with('android_version', '=', '4.2', 'and')->once()->andReturn($builder);
$builder->shouldReceive('where')->with('orientation', '=', 'Vertical', 'or')->once()->andReturn($builder);

$builder->dynamicWhere($method, $parameters);
}


public function testCallTriggersDynamicWhere()
{
$builder = $this->getBuilder();

$this->assertEquals($builder, $builder->whereFooAndBar('baz', 'qux'));
$this->assertCount(2, $builder->wheres);
}


/**
* @expectedException BadMethodCallException
*/
public function testBuilderThrowsExpectedExceptionWithUndefinedMethod()
{
$builder = $this->getBuilder();

$builder->noValidMethodHere();
}


protected function getBuilder()
{
$grammar = new Illuminate\Database\Query\Grammars\Grammar;
Expand Down