简体   繁体   中英

Nested Query in Laravel 5.2

I Have a search box that I want to use to search some of columns of a table in the database. Here's the code

$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'));

The data as it is when the page loads is filtered to show just the items from this project. But when the search is done, it searches the whole table. How can I make it search only the items from the specific project and not the whole items from the table?

You can nest your search items this way:

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'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM