繁体   English   中英

我可以在Laravel5上使用case方法追加吗?

[英]Can I use case method append on Laravel5?

我这样写代码

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

有人知道什么样的解决方案吗?

使用此代码

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

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

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

您可以这样做:

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

然后,当您想要添加任何内容时,请像这样添加它:

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

您不需要使用.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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