doushen1026 2015-05-06 17:26 采纳率: 100%
浏览 55
已采纳

我可以使用Laravel 5链接可变数量的查询范围

My users need to be able to query the database with up 5 different parameters. I think the best way to handle this is with query scopes. Then just chain together the query scopes. But I cannot figure out how to do this based on an unknown number (0-5) of search parameters.

I have it working with one specific search parameter.

$thirtyDaysAgo = Carbon::now()->subDays(30)->toDateString();
$orders = Order::DateRange($thirtyDaysAgo)->get();
return view('orders/browse', compact('orders'));

Any help would be appreciated.

Edit: More info

Parameters are posted to the page from a form:

$input = Input::all();
dd($input);

yields

array:7 [▼
"_token" => "MX4gVmbON56f9Aa88kgn2Re68GoDrtDeR6phEJ30"
"orderType" => "1"
"orderNumber" => "1"
"timePeriod" => "0"
"orderStatus" => "0"
"sku" => ""
"customer" => "0"
]

Edit: Adding query scopes

public function scopeDateRange($query, $range){
    return $query->where('created_at', '>=', $range);
}

public function scopeOrderNumber($query, $orderNumber){
    return $query->whereOrderNumber($orderNumber);
}

public function scopeCustomer($query, $customer){
    return $query->whereCustomerId($customer);
}

public function scopeStatus($query, $status){
    if($status == 'active'){
        return $query->where('orderStatus_id', '!=', 15)->where('orderStatus_id', '!=', 10);
    }elseif($status == 'complete'){
        return $query->whereOrderStatusId(15);
    }elseif($status == 'cancelled'){
        return $query->whereOrderStatusId(10);
    }
}
  • 写回答

2条回答 默认 最新

  • dongshi1102 2015-05-06 18:35
    关注

    By the looks of it, you are going to want to just check to see if your parameters are empty, and if so, you can just return the query and not perform the scope check:

    public function scopeDateRange($query, $range){
        if (!empty($range)) {
            return $query->where('created_at', '>=', $range);
        }
        else {
            return $query;
        }
    }
    

    Then, you can just chain them all together and the scope functions will sort out whether or not to filter the query all by themselves.

    $orders = Order::dateRange($range)->orderNumber($orderNumber)->customer($customer)->status($status)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来