Reputation: 356
I am trying to create a more advanced query in Laravel 4, which consists of AND and OR where clauses, in the following format:
(('a','=','1') OR ('b','=','s') OR ('c','=','3')) AND (('d','=','1') OR ('e','=','s') OR ('f','=','3'))
The problem is that I am generating these queries on the fly, based on some filters the user applies through some forms. This means that the query can have the following format:
a AND b
as well as this format:
(a OR b OR c) AND (d OR e OR f)
as well as this one:
(a OR b) AND c AND (d OR e) AND f
I am generating the where clause as a string, but I cannot manage to add this variable to the method call.
Example:
$whereclause = where(function($query){$query->where('colorgrade','like','41-2');})->where(function($query){$query->where('datetime','>','2014-11-05');})
$result = $gin->bales()->$whereclause->take(1000)->get();
The error I am getting is the following:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$where(function($query){$query->where('colorgrade','like','41-2');})->where(function($query){$query->where('datetime','>','2014-11-05');})
How can I pass the generated where clause (string variable) to the above chaining functions?
Upvotes: 0
Views: 2534
Reputation: 371
To create queries on the fly, is a good ideia make use of Eloquent Query Scopes. That's provide a way for you to build different queries based on, for example, form options.
http://laravel.com/docs/4.2/eloquent#query-scopes
Upvotes: 1
Reputation: 9883
You may be able to do it like this, however I have a hunch this doesn't work with closures and chained methods in the variable. See http://php.net/manual/en/functions.variable-functions.php
$result = $gin->bales()->$whereclause()->take(1000)->get();
Alternativly you can split up the query so its not all done within a single line.
// Get the initial Query Builder instance
$query = $gin->bales();
$query->where(function($query) {
$query->where('colorgrade', 'like', '41-2');
});
if ($something === 'something') {
$query->where('something', $something);
} else {
$query->where('something', 'something_else');
}
// Finally get our results
$results = $query->take(1000)->get();
Upvotes: 0