vendredi 14 octobre 2016

looping through array to get data using eloquent inside eloquent query

I'm programming a tourism agency website. I've hotels in database which have a column called stars which is an integer its value is between 1 to 5.

I have a form which the user can search hotels based on their stars. The field is checkbox so he can search five stars and four stars hotels together for example.

I read the stars array and redirect the visitor to the search page using this code:

$stars_param = "";
    $i = 1;
    foreach($stars as $star){
        if($i == 1){
            $stars_param .= $star; 
        }else{
            $stars_param .= "&".$star;
        }
        $i++;
    }
    $parameters = "filter=true&&stars=".$stars_param."&&price=".$price."&&area=".$area;
    return \Redirect::to('/hotels-search/?'.$parameters); 

So the url will be like this:

hotels-search?filter=true&&stars=5&1&&price=300&&area=taksim

And in the hotels-search page I read the $_GET , and explode the stars variable and coded this query to fetch data:

$stars = $_GET['stars'];
$stars_array = explode('&', $stars);
$price = $_GET['price'];
$area = $_GET['area'];
$this['hotels'] = \Lilessam\Hotels\Models\Hotel::orderBy('id', 'desc')->where('stars',  function($query) use($stars_array){
                $i = 1;
                foreach($stars_array as $star){
                    if($i == 1){
                        $query->where('stars', $star);
                    }else{
                        $query->orWhere('stars', $star);
                    }
                    $i++;
                }

                })->where('price', '<=', $price)->whereHas('area', function($query) use($area){
                                $query->where('name', 'LIKE', $area);
                                })->paginate(5);

But with this I got this error from database !

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where `stars` = ?) and `price` >= ? and (select count(*) from `lilessam_hotels_a' at line 1 (SQL: select count(*) as aggregate from `lilessam_hotels_hotels` where `stars` = (select * where `stars` = 5) and `price` >= 300 and (select count(*) from `lilessam_hotels_areas` where `lilessam_hotels_hotels`.`area_id` = `lilessam_hotels_areas`.`id` and `name` LIKE taksim) >= 1)

How can I make a query so I can get hotels with 1 or 3 or 5 stars at the same time?!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire