Laravel 在所有列中过滤一个值

Laravel filter a value in all columns

public function getBooks($input)
{
    $books= Book::where('book_name', 'LIKE', '%' . $input . '%')->get();
    return Response::json($books);
}

我知道如何按给定值过滤列。但是如何按给定值过滤所有列。例如,我有一个名为 'category' 的列,用户应该可以在其中使用相同的搜索栏来过滤类别。

类似于:

$books = Book::where('all_columns', 'LIKE', '%' . $input . '%')->get();

谢谢!

大多数数据库不支持同时搜索所有列。恐怕您可能必须将所有列链接在一​​起:

$books = Book::where('book_name', 'LIKE', '%' . $input . '%')
    ->orWhere('another_column', 'LIKE', '%' . $input . '%')
    // etc
    ->get();

您必须像@JoelHinz 建议的那样为每一列添加一个 where 子句。为了稍微简化一下,您可以使用数组和循环:

$query = Book::query();
$columns = ['book_name', 'foo', 'bar'];
foreach($columns as $column){
    $query->orWhere($column, 'LIKE', '%' . $input . '%');
}
$books = $query->get();

或者甚至使用架构构建器从您的 table:

中检索所有列名
$columns = Schema::getColumnListing('books');

您还可以使用此覆盖功能将条件应用于所有行。

public function newQuery($excludeDeleted = true) {
        return parent::newQuery()
            ->where('another_column', 'LIKE', '%' . $input . '%');
    }

现在图书模型将只提供符合您要求的结果。