我写这样的代码
$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();
任何人都知道善解决方案吗?
答案 0 :(得分: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();
答案 1 :(得分:0)
你可以这样做:
$lists = \App\Test::where('created_at', '<=', 'now()');
然后当你想要追加任何东西时,像这样添加:
if(!empty($category)){ // ?category=1, category=2
$lists = $lists::where('category','=', $category);
}
您不需要使用.