[英]Laravel 4 multiple field search
我對laravel 4多重搜索有一個疑問。
我有需要檢查的變量,它是否為空,我想知道,還有其他方法可以執行此操作嗎?
到目前為止,我嘗試這樣做,但這似乎還不夠好。
編碼:
public function postQuickSearch() {
$vehicle_manufacturer = Input::get('vehicle_manufacturer');
$vehicle_model = Input::get('vehicle_model');
$year_reg_from = Input::get('year_reg_from');
$year_reg_to = Input::get('year_reg_to');
$price_from = Input::get('price_from');
$price_to = Input::get('price_to');
if(!empty($year_reg_from) && !empty($year_reg_to)) {
$query = Seller::where('vehicle_manufacturer', 'LIKE', '%'. $vehicle_manufacturer .'%')->orWhere('vehicle_model', 'LIKE', '%'. $this->getModel($vehicle_model) .'%')->whereBetween('year_reg', array($year_reg_from, $year_reg_to))->get();
}
if(!empty($price_from) && !empty($price_to)) {
$query = Seller::where('vehicle_manufacturer', 'LIKE', '%'. $vehicle_manufacturer .'%')->orWhere('vehicle_model', 'LIKE', '%'. $this->getModel($vehicle_model) .'%')->whereBetween('price', array($price_from, $price_to))->get();
}
if(empty($price_from) && empty($price_to) && empty($year_reg_from) && empty($year_reg_to)) {
$query = Seller::where('vehicle_manufacturer', 'LIKE', '%'. $vehicle_manufacturer .'%')->orWhere('vehicle_model', 'LIKE', '%'. $this->getModel($vehicle_model) .'%')->get();
}
if($query->count()) {
$data = array(
'results' => $query
);
return View::make('auto.vehicle.search')->with($data);
}
return Redirect::route('home')->with('global', 'No results.');
}
謝謝你的幫助。 :)
好吧,您可以刪除初學者的代碼重復。 只需嘗試將看起來相似的所有內容歸為一組即可。
例:
public function postQuickSearch() {
$fields = array(
'vehicle_manufacturer','vehicle_model',
'year_reg_from','year_reg_to',
'price_from','price_to'
);
foreach($fields as $field)
$$field = Input::get($field);
$query = Seller::where('vehicle_manufacturer', 'LIKE', '%'. $vehicle_manufacturer .'%')
->orWhere('vehicle_model', 'LIKE', '%'. $this->getModel($vehicle_model) .'%');
if(!empty($year_reg_from) && !empty($year_reg_to)) {
$query->whereBetween('year_reg', array($year_reg_from, $year_reg_to));
}
if(!empty($price_from) && !empty($price_to)) {
$query->whereBetween('price', array($price_from, $price_to));
}
if(empty($price_from) && empty($price_to) && empty($year_reg_from) && empty($year_reg_to)) {
//Nothing yet
}
$result = $query->get();
if($result->count()) {
$data = array(
'results' => $result
);
return View::make('auto.vehicle.search')->with($data);
}
return Redirect::route('home')->with('global', 'No results.');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.