laravel 如何从数据库中的多列获取搜索查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48089966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Get Search Query From Multiple Columns in Database
提问by Yudy Ananda
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
问题是我从请求中获得的数据仅适用于judul。如果输入关键字搜索针对搜索作者或发布者,它只会显示空结果
I want the search form able to get data from other columns named writtersand publisher
我希望搜索表单能够从名为writters和publisher 的其他列中获取数据
Is there any method to get data from multiple column?
有没有什么方法可以从多列中获取数据?
回答by Rits
You can use orwhere to fullfill this, like this
你可以使用 orwhere 来完成这个,就像这样
Book::where(function ($query) use($keyword) {
$query->where('judul', 'like', '%' . $keyword . '%')
->orWhere('writters', 'like', '%' . $keyword . '%');
})
->get();
I hope it helps you.
我希望它能帮助你。
回答by Alexey Mezenin
You can execute conditional queries in many ways.
您可以通过多种方式执行条件查询。
1.You can use when()
:
1.您可以使用when()
:
Book::when($keyword, function ($q) use ($keyword) {
return $q->where('judul', 'LIKE', '%' . $keyword . '%');;
})
->get();
2.Use the where closure:
2.使用where 闭包:
Book::where(function($q) use ($keyword, $request) {
if ($request) {
$q->where('judul', 'LIKE', '%' . $keyword . '%');
}
})
->get();
3.Do this:
3. 这样做:
$books = Book::query();
if ($request) {
$books = $books->where('judul', 'LIKE', '%' . $keyword . '%');
}
$books = $books->get();