質問

条件付き 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()
    ]);
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top