2016-09-07 5 views
0

私は仕事が、私は汚いコードを考えているこのLaravel5でcaseメソッドappendを使用できますか?

$category = Input::get('category'); // ?category=1 

    if(!empty($category)){ // ?category=1, category=2 
     $lists = \App\Test::where('created_at', '<=', 'now()') 
           ->where('category', $category) // append this. 
           ->orderBy('id','desc') 
           ->get(); 
    } 
    else { // ?category=, category=0 
     $lists = \App\Test::where('created_at', '<=', 'now()') 
           ->orderBy('id','desc') 
           ->get(); 
    } 

のようなコードを記述します。 できれば同じコードをもう一度書いてはいけません。

だから私は、誰もが優しいソリューションを知っている

$category = Input::get('category'); // ?category=1 

    $lists = \App\Test::where('created_at', '<=', 'now()'); 

    if(!empty($category)){ // ?category=1, category=2 
     $lists .= $lists::where('category', $category); 
    } 

    $lists .= $lists::orderBy('id','desc')->get(); 

(動作していない)、このように行いたいですか?

答えて

1

使用あなたはそれが好き行うことができます。このコード

$lists = \App\Test::where('created_at', '<=', 'now()'); 

    if(!empty($category)){ // ?category=1, category=2 
     $lists = $lists->where('category', $category); 
    } 

    $lists->orderBy('id','desc')->get(); 
+0

WORK !!素晴らしい! D – qwe001

+0

あなたは歓迎です –

+0

@ qwe001あなたの問題を解決するのを手助けした人を奨励し、同様の問題を抱えている訪問者を助けるための答えとしてマークしてください... – Poiz

0

$lists = \App\Test::where('created_at', '<=', 'now()'); 

、あなたが何かを追加したいときに、このようにそれを追加する:

if(!empty($category)){ // ?category=1, category=2 
    $lists = $lists::where('category','=', $category); 
} 

あなたはドン使用する必要はありません.

関連する問題