[英]Laravel: Query string to Eloquent filter
我需要一個小的函數,它將一個查詢字符串並將其轉換為3個查詢之一:
這是我目前正在做的事情:
// USE: ?price[between][min]=0&price[between][max]=100&size[in][value]=L&size[in][value]=M
$filters = ['price', 'size'];
$products= Product::query();
foreach($filters as $filter)
{
if(isset($input[$filter]) && array_filter($input[$filter][key($input[$filter])]))
{
sort($input[$filter][key($input[$filter])]);
$products->{'where' . ucfirst(key($input[$filter]))}($filter, $input[$filter][key($input[$filter])]);
}
}
return $products->get();
這是我的問題:
您可能對該查詢字符串有一些問題,因為var_dump會導致以下問題:
array(2) {
'price' =>
array(1) {
'between' =>
array(2) {
'min' => string(1) "0"
'max' => string(3) "100"
}
}
'size' =>
array(1) {
'in' =>
array(1) {
'value' => string(1) "M"
}
}
}
您會看到缺少可變size
的值L
,因為它已被M
替換。 當然,您可以添加另一個數組,但是如果可以簡化為以下形式:
?price[between]=0,100&size[in]=L,M
無論如何,出於可讀性考慮,我更喜歡此代碼。
$qString = Input::all();
$model = App::make('Product');
$products = $model->where(function($query) use($qString) {
foreach($qString as $column => $operations) {
foreach($operations as $operator => $values) {
switch($operator) {
case 'between':
$query->whereBetween($column, array($values['min'], $values['max']));
break;
case 'in':
$query->whereIn($column, $values);
break;
}
// or replace the switch with this:
// $query->{'where' . ucfirst($operator)}($column, $values);
}
}
})->get();
請注意,這尚未經過測試(盡管我在Repository方法中使用了閉包並且它們可以工作),您可能需要對此進行一些調整。
另請注意,如果您選擇一個我建議的查詢字符串,則可能需要進行一些驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.