Laravel 5.2中的嵌套查询

时间:2016-12-28 21:28:38

标签: php laravel eloquent laravel-5.2

我有一个搜索框,我想用它来搜索数据库中某些表的某些列。这是代码

$project = Project::findOrFail($id);
    $file = \App\File::find($file);
    $query = $request->input('q');                   
    $materials = $query
        ?\App\Material::where('file_id', '=', $file->id)
                        ->where('material_name', 'LIKE',  "%$query%" )->get()
        :\App\Material::where('file_id', '=', $file->id)->get();


     return view('projects.file',compact('project', 'file', 'materials'));

过滤页面加载时的数据,仅显示此项目中的项目。但是当搜索完成后,它会搜索整个表格。如何才能仅搜索特定项目中的项目而不搜索表格中的所有项目?

1 个答案:

答案 0 :(得分:2)

您可以通过以下方式嵌套搜索项目:

public function handle($request, Closure $next)
{
    $project = Project::findOrFail($id);

    $file = \App\File::find($file);

    $materials = \App\Material::newQuery();

    // Did it found the file?    
    if ($file) {
        // Search for the file
        $materials->where('file_id', '=', $file->id);
    }

    // AND, does it have a query to search?
    if ($search_item = $request->input('q')) {
        // Search for the query
        $materials->where('material_name', 'LIKE',  "%$search_item%");
    }

    // AND, does it have a project to filter?
    if ($search_item = $request->input('project')) {
        // Filter the project 
        $materials->where('project', 'LIKE',  "%$search_item%");
    }

    // Now go get the results
    $materials = $materials->get();

    // And return to the view
    return view('projects.file',compact('project', 'file', 'materials'));
}