以下是我print_r($_POST)
array([id] => '123', [name] => '', [place] => '', [color] => '')
name
,place
和color
是用户提交的可选字段.....用户可以只选择name
,place
或{{ 1}},color
,name + 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
。但是,如果有许多可选输入怎么办?
答案 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);
}