【问题标题】:Filtering in Laravel using regex使用正则表达式在 Laravel 中过滤
【发布时间】:2019-11-16 20:16:38
【问题描述】:


我正在尝试根据查询字符串过滤产品。我的目标是从集合中获取产品(如果已提供),否则获取所有产品。有人可以帮我看看下面的代码有什么问题吗?

$products = \App\Product::where([
'collection' => (request()->has('collection')) ? request('collection') : '[a-z]+',
'type' => (request()->has('type')) ? request('type') : '[a-z]+'
])->get();

PS.:我也尝试过 'regex:/[a-z]+',它不起作用...

$products = \App\Product::where(['collection' => (request()->has('collection')) ? request('collection') : 'regex:/[a-z]+'])->get();

【问题讨论】:

  • where 功能使用列、运算符和值...这些值是文字值,而不是 SQL 表达式、函数、列等
  • 除了@lagbox 评论,试试DB::raw('[a-z]+')
  • 如果这是使用 MySQL,您也许可以执行 where('collection', 'rlike', '[a-z]+') 或类似的操作

标签: php regex laravel laravel-5


【解决方案1】:

您可以做的是使用when eloquent 子句,因此只有当request('collection') 存在时才会触发集合的where 子句,同样的逻辑也适用于类型。

$products = \App\Product::
when(request()->has('collection'), function ($q) {
    return $q->where('collection', request('collection'));
});
->when(request()->has('type'), function ($q) {
    return $q->where('type', request('type'));
})
->get();

或者另一种方式,如果您将 request 值分配给类似的变量:

    $collection = request('collection');
    $type= request('type');

        $products = \App\Product::
        when(!empty($collection), function ($q) use ($collection) {
            return $q->where('collection', $collection);
        });
        ->when(!empty($type), function ($q) use ($type) {
            return $q->where('type', $type);
        })
        ->get();

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多