Currently, a user can add a criteria which is searched amongst our database to find any matching results. This is working perfectly, however, there is now a need to 'enhance' the search. To help make things clearer, there is a working example below:
Scenario
A user wants to buy
a property:
location
4
bedrooms detached
This is added to the database, and then the function below finds any matching properties (shortened):
$locations = Location::whereHas('coordinate', function ($q) use
($bedrooms, $property_type)
{
$q->where('bedrooms', '=', $bedrooms)
->where('type', '=', $property_type);
})->lists('id');
So as you can see, the query is pretty 'set' on just querying one
number of bedrooms and one
property type' - it's just one variable on the same row!
Now, the problem.
Currently, a user can add one preference of bedrooms, type of house
etc... The change is to add multiple choice
for bedrooms, type of house
etc... So the new query
would be for a user:
Proposed scenario
location
(this is always one location) 3,4,5,6
bedrooms detached, studio, semi-detached, bungalow
My question is mainly advice, how can I store such a query, and then query it back to return any properties that match their criteria. Each criteria currently exists on one row, but I imagine I'll have to have a separate table to store the number of bedrooms etc...?
Also, for example, if one user only wants 1
bedrooms and detached, studio, semi-detached, bungalow
, as opposed to another user whose criteria may be far more in depth, how can a query accommodate this?
Instead of completely redesigning my tables, could I not serialize the number of bedrooms etc.. and then store them in VARCHAR, and un-serialize them on request?
I hope I've explained things clearly, including providing my current code. If you require further information please just let me know. Many thanks in advance.
You could use logic to control the where clauses depending on what values are set and/or if they are an array. Instead of chaining the where statements you could write:
//bedrooms (required, mixed)
if(is_array($bedrooms)){
$q->whereIn('bedrooms', $bedrooms)
}else{
$q->where('bedrooms', '=', $bedrooms)
}
//type (required, mixed)
if(is_array($property_type)){
$q->whereIn('type', $property_type)
}else{
$q->where('type', '=', $property_type)
}
//minimum price (optional, int)
if(isset($min_price)){
$q->where('price', '>=' , $min_price)
}
//maximum price (optional, int)
if(isset($max_price)){
$q->where('price', '<=' , $max_price)
}
This is just a fast example based on what you provided but I would probably see how you could refactor the call or the values you are passing to the query to try and increase the code readability.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.