쿼리를 작성과 조건부가 절에서 변 모델
문제
나를 구축 할 필요가 쿼리로 웅변을 포함하는 모델을 조건 where.내가 무언가를 만들었을 검색하여 google.하지만 그것은 없는 것 같습니다.
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);
는 완벽하게 작동하는 지금.그러나 만약 누군가가 몇 가지 더 나은 옵션을 제안하십시오.감사합니다.
다른 팁
모델에 범위를 추가하고 컨트롤러에서 전화하십시오.이렇게하면 실제 필터링 작업이 모델에서 수행되면 컨트롤러가 필터 범위를 통해 쿼리를 실행 중입니다.
모델 :
Input::get
로 URL 매개 변수를 가져오고 있지만 함수에 대한 입력 매개 변수로 전달합니다.
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