laravel 在 eloquent 模型中使用条件 where 子句构建查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24008715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:35:45  来源:igfitidea点击:

build a query with conditional where clause in eloquent model

mysqllaraveleloquentbuilder

提问by Krishna Raj K

I need to build a query with eloquent model including conditional where clause. I created something by searching google. But it doesn't seems to be working.

我需要用雄辩的模型构建一个查询,包括条件 where 子句。我通过搜索谷歌创造了一些东西。但它似乎不起作用。

if ($status) {
    $this->where('status', $status);
}
if ($assignedto) {
    $this->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
    $this->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $this->orderBy('date', 'desc')->paginate(40);

This one returns all results without the filtering of status, assigned to and dates.

这个返回所有结果,没有过滤状态、分配给和日期。

采纳答案by Krishna Raj K

I just updated it by assigning $thisto a new variable because when I assigned the query to $this, it shown an error, $thiscannot be over written.

我只是通过分配$this给一个新变量来更新它,因为当我将查询分配给 时$this,它显示了一个错误,$this不能被覆盖。

$quoteModel = $this;
if ($status) {
    $quoteModel = $quoteModel->where('status', $status);
}
if ($assignedto) {
    $quoteModel = $quoteModel->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
    $quoteModel = $quoteModel->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $quoteModel->orderBy('date', 'desc')->paginate(40);

which works perfectly now. But if somebody have some better option, please suggest. Thanks.

现在完美运行。但如果有人有更好的选择,请提出建议。谢谢。

回答by Thomas Jensen

I added a scope to my model and call it from the controller. This way the actual filtering work is done in the model, the controller is just running the query through the filter scope.

我向我的模型添加了一个范围并从控制器调用它。通过这种方式,实际的过滤工作在模型中完成,控制器只是通过过滤器作用域运行查询。

Model:

模型:

I am getting URL parameters with Input::get, but you would also pass them as input parameters to the function.

我使用 获取 URL 参数Input::get,但您也可以将它们作为输入参数传递给函数。

public function scopeFilter($query)
{
    $published = Input::get('published');
    if (isset($published)) $query->where('published', '=', $published);

    return $query;
}

Controller:

控制器:

Here the query is run through the filter()before returning it to the view.

这里查询filter()在返回到视图之前运行。

public function index()
{
    return View::make('articles.index', [
        'articles' => Article::with('writer')->filter()->get()
    ]);
}