drhqkz3455 2016-10-14 10: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 11: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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度