简体   繁体   中英

Can I use case method append on Laravel5?

I write code like this

    $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();
    }

That is so work but I think dirty code. I dont wanna write same code again if I can.

So I wish to do like this ( Not working )

    $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();

Anyone know kind solutions?

Use this code

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

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

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

You can do it like:

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

and then when you want to append anything, add it like this:

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

you don't need to use .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM