在eloquent where语句中应用查询字符串的最佳方法是什么?

时间:2017-06-11 17:57:47

标签: php laravel search query-string

想象一下,我们有一些像这样的查询字符串:

  • example.com/posts?param1=val1&param2=val2&param3=val3..

我正在使用以下脚本,但我知道这不是标准和最好的方式,实际上它是我见过/做过的最糟糕的!

在数据库中搜索文件:

    $data = [
        'files' => File::orderBy('id','desc')->paginate(12),
    ];

    //Adding query strings
    if (!empty($request->search)) {

        $replacement_data = [
            'files' => File::where('name','LIKE',"%$request->search%")->paginate(12),
        ];

        return view ("manage.Files.index")->withData(array_replace($data,$replacement_data));

    }

    else {
        return view ("manage.Files.index")->withData($data);
    }

现在我的问题很清楚,如何在SQL / Eloquent where语句中使用这些查询字符串作为过滤器?

1 个答案:

答案 0 :(得分:2)

您可以动态生成查询。我在项目中的方式是依赖注入Model类。

private $model;

public function __construct(File $model)
{
    $this->model = $model;
}

public function search(Request $request) {

    $query = $this->model;

    // add query string to limit search or ..
    if (!empty($request->search)) {
         $query = $query->where('name','LIKE',"%$request->search%");
    }

    $data['files'] = $query->orderBy('id','desc')->paginate(12);

    return view ("manage.Files.index")->withData($data);

}