在 Eloquent 模型中使用条件 where 子句构建查询
题
我需要使用包含条件 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
到一个新变量,因为当我将查询分配给 $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);
现在效果很好。但如果有人有更好的选择,请提出建议。谢谢。
其他提示
我向模型添加了一个范围并从控制器调用它。这样,实际的过滤工作是在模型中完成的,控制器只是通过过滤器范围运行查询。
模型:
我正在获取 URL 参数 Input::get
, ,但您也可以将它们作为输入参数传递给函数。
public function scopeFilter($query)
{
$published = Input::get('published');
if (isset($published)) $query->where('published', '=', $published);
return $query;
}
控制器:
这里查询是通过 filter()
在将其返回视图之前。
public function index()
{
return View::make('articles.index', [
'articles' => Article::with('writer')->filter()->get()
]);
}
不隶属于 StackOverflow