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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog