使用 laravel 进行全局搜索

Global search with laravel

我编写了一个代码来在数据中进行搜索 table,从而输入 ID 和客户名称,但我需要在不指定列的情况下搜索额外的字段。

我需要按列搜索,有带搜索功能的控制器:

public function search(Request $request)
    {

        if ($request->ajax()) {

            $output = "";
            $indents = DB::table('indents')
                ->where('id', 'LIKE', '%' . $request->search . '%')
                ->orwhere('customer_name', 'LIKE', '%' . $request->search . '%')
                ->orwhere('*', 'LIKE', '%'.$request->search. '%')
                ->get();
                $count=1;
            foreach ($indents as $key => $indent) {


                    $output .= '<tr>' .
                    '<td>'.$count++.'</td>'.
//                    '<td>' . $indent->id . '</td>' .
                    '<td>' . $indent->customer_name . '</td>' .
                    '<td>' . $indent->phone_no . '</td>' .
                    '<td>' . $indent->date_of_delivery . '</td>' .
                    '<td>' . $indent->delivery_at . '</td>' .
                    '<td>' . '.<a href="' . route('edp.show', $indent->id) . '">.' . '<img src="assets/images/select.jpg" class="imgsize">.' . '</a>.' . '</td>' .
                    '</tr>';

            }
            return Response($output);
        }

    }

您可以使用 Laravel 计数 Laravel Scout

或者您可以自己实现,使用 mysql Mysql Full-text Search

您可以像这样搜索一组列:

$columnsToSearch = ['column1', 'column2', 'column3'];

如果您需要从 frontend/api 传递这些列,这些列可以是 $request 的一部分。

然后遍历每个 $columnsToSearch 并像这样添加到您的查询构建器中:

$columnsToSearch = ['column1', 'column2', 'column3'];
// or $columnsToSearch = $request->input('columns_to_search');

$searchQuery = '%' . $request->search . '%';

$indents = DB::table('indents')
            ->where('id', 'LIKE', $searchQuery);

foreach($columnsToSearch as $column) {
    $indents = $indents->orWhere($column, 'LIKE', $searchQuery);
}

$indents = $intents->get();

您可以获得所有 table 列:

$columns = DB::getSchemaBuilder()->getColumnListing('indents');

然后为每一列添加 orwhere() 条件。但请注意,对于大 tables 的搜索会很慢,除非您添加索引。