Laravel 多条件搜索查询

做查询功能时,输入的关键词有的为空,有的有值,如何实现多功能查询呢?这里介绍一种方法。(基于laravel)

原理很简单,第一步:判断接收的值,第二步:写查询语句。具体实现如下:

   //首先,创建句柄: 

 $handle = DB::table('classrooms');

//判断接收的值是否为空
$keywords1 && $handle->where('field_name','like','%' . $keywords1 . '%');
也可以写成:if($keywords1){$handle->where('field_name','like','%' . $keywords1 . '%');
// 判断接收的值是否为空
$keywords2 && $handle->where('field_name','like','%' . $keywords2 . '%');

...

// 获取数据
$handle->get();
代码可以精简如下:
$handle = DB::table('classrooms');
$keys = $request->all();
foreach($keys as $key => $val){
$keys[$key] && $handle->where($key,'like','%' . $val . '%');
}
// 获取数据
$datas = $handle->get();
摘自:https://segmentfault.com/q/1010000007556256?_ea=1386542
记录点滴,迭代精进,追求新生。Email: 942298768@qq.com
原文地址:https://www.cnblogs.com/chaoyong/p/8137279.html