How To Get Search Query From Multiple Columns in Database

假装没事ソ 提交于 2019-12-22 10:59:03

问题


I have search form to get information from table named books.

Right now i'm using this controller

public function search(Request $request)
{
    $keyword = $request->input('keyword');
    $query = Book::where('judul', 'LIKE', '%' . $keyword . '%');

    $book_list = $query->paginate(5);
    $pagination = $book_list->appends($request->except('page'));
    $total_book = $book_list->total();
    return view('dashboards.index', compact('book_list', 'keyword', 'pagination', 'total_book'));
}

The problem is the data that i get from the request only available for judul. it just show empty result if the input keyword search addressed to search writter or publisher

I want the search form able to get data from other columns named writters and publisher

Is there any method to get data from multiple column?


回答1:


You can use orwhere to fullfill this, like this

Book::where(function ($query) use($keyword) {
        $query->where('judul', 'like', '%' . $keyword . '%')
           ->orWhere('writters', 'like', '%' . $keyword . '%');
      })
->get();

I hope it helps you.




回答2:


You can execute conditional queries in many ways.

1. You can use when():

Book::when($keyword, function ($q) use ($keyword) {
        return $q->where('judul', 'LIKE', '%' . $keyword . '%');;
    })
    ->get();

2. Use the where closure:

Book::where(function($q) use ($keyword, $request) {
        if ($request) {
            $q->where('judul', 'LIKE', '%' . $keyword . '%');
        }
    })
    ->get();

3. Do this:

$books = Book::query();

if ($request) {
    $books = $books->where('judul', 'LIKE', '%' . $keyword . '%');
}

$books = $books->get();


来源:https://stackoverflow.com/questions/48089966/how-to-get-search-query-from-multiple-columns-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!