laravel - 自定义搜索不起作用,多个字段

时间:2018-06-16 17:48:30

标签: php laravel search

我正在尝试为我的dashbord创建搜索,其中有4个字段,

所以我可以一个一个或两个同时搜索姓名,年龄,地点,电话,我写了一个代码,但它无法正常工作

    $q = Model::query();

  if (Input::has('name'))
  {
    $q->where('name',Input::get('name'));
  }

  if (Input::has('age'))
  {
    $q->where('age',Input::get('age'));
  }

  if (Input::has('location'))
  {
    $q->where('location', Input::get('location'));
  }

  if (Input::has('phone'))
  {
    $q->where('phone', Input::get('phone'));
  }

获得空输出:

[]

1 个答案:

答案 0 :(得分:2)

试试这个,

 $q = Model::select('id','name','age'); //What ever field you need, This will create model instance

  if (Input::has('name') && !empty(Input::get('name'))
  {
    $q->where('name',Input::get('name'));
  }

  if (Input::has('age') && !empty(Input::get('age'))
  {
    $q->where('age',Input::get('age'));
  }

  if (Input::has('location') && !empty(Input::get('location'))
  {
    $q->where('location', Input::get('location'));
  }

  if (Input::has('phone') && !empty(Input::get('phone'))
  {
    $q->where('phone', Input::get('phone'));
  }
$result = $q->get()->toArray(); 
print_r($result);

这应该可以为您提供所需的内容

相关问题