我正在尝试根据查询字符串过滤产品。我的目标是从集合中获取产品(如果有的话),否则获取所有产品。有人可以帮我以下代码有什么问题吗?
$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();
[您可以做的是使用when
雄辩的子句,因此,仅当request('collection')
存在时,才会触发用于集合的where子句,同样也要键入相同的logis。
$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'));
});
或者如果将request
值分配给类似变量的另一种方法:
$collection = request('collection');
$type= request('type');
$products = \App\Product::
when(request()->has('collection'), function ($q) use ($collection) {
return $q->where('collection', $collection);
});
->when(request()->has('type'), function ($q) use ($type) {
return $q->where('type', $type);
});