【问题标题】:Global search with laravel使用 laravel 进行全局搜索
【发布时间】:2018-09-15 02:09:13
【问题描述】:

我写了一个代码在数据表中搜索,输入一个 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);
        }

    }

【问题讨论】:

标签: php laravel laravel-5.5 laravel-5.6


【解决方案1】:

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

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

如果您需要从前端/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();

【讨论】:

    【解决方案2】:

    你可以使用 Laravel 账号Laravel Scout

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

    【讨论】:

      【解决方案3】:

      您可以通过以下方式获取所有表格列:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        • 2023-03-02
        • 2010-11-11
        相关资源
        最近更新 更多