laravel闭包函数查询

1.如下图代码示例实现了多条件的模糊查询并且如果没有参数传过来的时候返回全部的信息

 public function index(Request $request)
    {
            $data = Student::where(function ($query) use ($request) {
            $id = $request->input('id');
            $name = $request->input('name');
            $query->where('id', 'like', '%' . $id . '%')->where('sname', 'like', '%' . $name . '%');
        })->get()->toArray();
        return dd($data);
    }

2.Eloquent Orm多条件模糊查询:

public function index(Request $request)
    {
        // return Excel::download(new StudentExport(), 'student.xlsx');
        $data = Student::where(function ($query) use ($request) {
            $name =!empty($request->get('name'))?$request->get('name'):'';
            $id =!empty($request->get('id'))?$request->get('id'):'';
            $ide =!empty($request->get('ide'))?$request->get('ide'):'';
            $query->where('sname', 'like', '%' . $name . '%');
            //$query->where('id','like','%'.$request->get('id').'%');
            if ($id!=$ide){
                $query->whereBetween('id',[$id,$ide] );
            }
            //$query->whereBetween('id', '<=', $ide);
        })->get()->toArray();
        return dd($data);
    }
posted @ 2020-05-10 20:23  以己为镜  阅读(2156)  评论(0编辑  收藏  举报