drhqkz3455 2016-10-14 02:47
浏览 40
已采纳

循环遍历数组以使用雄辩的内部雄辩查询来获取数据

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(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 if I search hotels with 5 and 1 stars, I only get the five stars hotels!

if I search hotels with 4 and 3 stars, I only get the four stars hotels ! Other times I get nothing from database at all !!

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

展开全部

  • 写回答

2条回答 默认 最新

  • douyi1779 2016-10-14 03:03
    关注

    Why don' you use this

    $this['hotels'] = \Lilessam\Hotels\Models\Hotel::orderBy('id', 'desc')
                        ->whereIn('start',$stars_array)
                        ->where('price', '<=', $price)
                        ->whereHas('area', function($query) use($area){
                                $query->where('name', 'LIKE', $area);
                                })->paginate(5);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部