Laravel Query Builder:基于用户输入的条件

时间:2014-06-25 05:22:19

标签: php laravel laravel-4

以下是我print_r($_POST)

的输出

array([id] => '123', [name] => '', [place] => '', [color] => '')

nameplacecolor是用户提交的可选字段.....用户可以只选择nameplace或{{ 1}},colorname + color或全部三个color + place

如何为用户选择的这些选项设置name + color + place条件?比方说,例如,在Laravel中,我们使用以下语句选择DB表...

where

正如您所看到的,上述条件仅在用户输入所有字段时才有效,根据用户输入我想添加 $Select_db = Db::table('mytable') ->where('name', Input::get('name')) ->where('place', Input::get('place')) ->where('color', Input::get('color')) ->select() ->get(); 条件,我们该怎么解决这个问题?

注意:在这个特定场景中,我知道我可以对每个条件使用where。但是,如果有许多可选输入怎么办?

3 个答案:

答案 0 :(得分:4)

试试这个: -

$Select_db = DB::table('mytable');

if (Input::get('name') != "")
    $Select_db->where('name', Input::get('name'));

if (Input::get('place') != "")
    $Select_db->where('place', Input::get('place'));

if (Input::get('color') != "")
    $Select_db->where('color', Input::get('color'));

$result = $Select_db->get();

如果有多列要匹配,请尝试使用: -

$Select_db = DB::table('mytable'); 
foreach($_POST as $key => $val){
    if(Input::get($key) != ""){
        $Select_db->where($key, Input::get($key));
    }   
} 
$Select_db->get();

答案 1 :(得分:0)

怎么样

$Select_db = Db::table('mytable');
foreach($_POST as $key => $val) {
    $Select_db->where($key, Input::get($key));
}
$Select_db->query()->get();

在您输入$_POST之前,可以考虑复制foreach并删除不需要的值:

unset($postcopy['badvar'])

答案 2 :(得分:0)

  public function filter(Request $request)
  {   
    $first_name = $request->input('first_name');
    $sur_name = $request->input('sur_name');
    $email_work = $request->input('email_work');
    $country = $request->input('country');
    $position = $request->input('position');
    $event_id = $request->input('event_id');
    $event_name = $request->input('event_name');
    $nature_of_business = $request->input('nature_of_business');
    $mobile_number = $request->input('mobile_number');
    $event_date = $request->input('event_date');

        $record = DB::table('exceldatas');
        if ($request->has('first_name')){
            $record->where('first_name', $first_name);
        }
        if ($request->has('sur_name')) {
           $record->where('sur_name', $sur_name);
        }
        if ($request->has('email_work')) {
            $record->where('email_work', $email_work);
        }
        if ($request->has('country')) {
            $record->where('country', $country);
        }
        if ($request->has('event_name')) {
            $record->where('event_name', $event_name);
        }
        if ($request->has('nature_of_business')) {
            $record->where('nature_of_business', $nature_of_business);
        }
        if ($request->has('mobile_number')) {
            $record->where('mobile_number', $mobile_number);
        }
        if ($request->has('event_date')) {
            $record->where('event_date', $event_date);
        }
        $record =$record->paginate(15);
        return view('showresult')->with('record', $record);

}