Laravel 过滤所有列中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28543166/
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
Laravel filter a value in all columns
提问by Robert M. Tijerina
public function getBooks($input)
{
$books= Book::where('book_name', 'LIKE', '%' . $input . '%')->get();
return Response::json($books);
}
I know how to filter a column by a given value. But how do I filter ALL columns by a given value. For example, I have a column called 'category' where user should be able to use the same search bar to filter the category.
我知道如何按给定值过滤列。但是如何按给定值过滤所有列。例如,我有一个名为“类别”的列,用户应该能够使用相同的搜索栏来过滤类别。
Something like:
就像是:
$books = Book::where('all_columns', 'LIKE', '%' . $input . '%')->get();
Thanks!
谢谢!
回答by lukasgeiter
You have to add a whereclause for each column like @JoelHinz suggests. To simplify things a bit you can use an array and a loop:
您必须where像@JoelHinz 建议的那样为每一列添加一个子句。为了简化一些事情,您可以使用数组和循环:
$query = Book::query();
$columns = ['book_name', 'foo', 'bar'];
foreach($columns as $column){
$query->orWhere($column, 'LIKE', '%' . $input . '%');
}
$books = $query->get();
Or even use the schema builder to retrieve all column names from your table:
或者甚至使用模式构建器从表中检索所有列名:
$columns = Schema::getColumnListing('books');
回答by Joel Hinz
Most databases do not support searching all columns simultaneously. I'm afraid you'll likely have to chain all of the columns together:
大多数数据库不支持同时搜索所有列。恐怕您可能不得不将所有列链接在一起:
$books = Book::where('book_name', 'LIKE', '%' . $input . '%')
->orWhere('another_column', 'LIKE', '%' . $input . '%')
// etc
->get();
回答by Safoor Safdar
You can also use this override function to apply condition to all rows.
您还可以使用此覆盖功能将条件应用于所有行。
public function newQuery($excludeDeleted = true) {
return parent::newQuery()
->where('another_column', 'LIKE', '%' . $input . '%');
}
Now Book Model will provide only result who match your requirement.
现在书籍模型将只提供符合您要求的结果。

