【问题标题】:What is the best way to apply query strings in eloquent where statements?在雄辩的 where 语句中应用查询字符串的最佳方法是什么?
【发布时间】:2017-06-11 17:57:47
【问题描述】:

假设我们有一些这样的查询字符串:

  • ?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 语句中使用这些查询字符串作为过滤器?

【问题讨论】:

  • 使用 laravel 的作用域通过请求数据过滤文件

标签: php laravel search query-string


【解决方案1】:

您可以动态生成查询。我在项目中所做的方式是依赖注入 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);

}

【讨论】:

  • 我觉得这样更好 $query = $query->where('name','LIKE',"%".$request->get('search',null)."% ");
  • 如果请求中没有传入搜索词,并不代表用户想通过'null'进行搜索。您的查询将返回不正确的结果,而不是返回所有文件。
  • 在您的情况下,如果在搜索中没有输入任何内容,值也会变为空白
  • 不,试试看。相当于File::orderBy('id', 'desc')->paginate(12);
猜你喜欢
  • 2014-09-20
  • 2017-09-15
  • 2017-10-18
  • 1970-01-01
  • 2014-01-03
  • 2021-09-29
  • 1970-01-01
  • 2019-03-02
  • 2012-05-31
相关资源
最近更新 更多