我的laravel网站上有一系列新闻报道.在/ news /页面上显示了一个快速的故事列表.
现在我想让用户过滤新闻.例如,仅显示“体育”故事.
在我的控制器中我这样做了:
$input = Input::all();
$events = DB::table('news')
->where('category', '=', $input['type'])
->order_by('created_at', 'desc')
->paginate(10);
现在,这允许我访问/ news?type = sports,它正确地只显示体育类别中的新闻项目.这仅在给出类型时才有效,如果没有给出类型,则显然会失败.
这是什么最好的解决方案?我知道我可以查看$input [‘type’]是否存在,如果存在,写一个全新的,第二个“$news = DB :: table(‘news’)…”代码,但我是以为我可能实际上想要多个用户输入,这会使该选项无效.例如,如果我想按类型和位置排序怎么办?像/ news?type = sports& area = chicago – 我该怎么办?
我知道我必须在这里遗漏一些明显的东西.谁能指出我正确的方向?
解决方法:
我想你可以使用foreach循环来做到这一点
$input = Input::all();
所以,你会得到这样的东西(你应该检查$input不是null)
Array
(
[type] => sports
[area] => chicago
)
现在,选择表格
$events = DB::table('news');
现在循环$input(对于多个动态where子句)
foreach ($input as $key => $value) {
$events->where($key, $value);
}
$result = $users->get();
或者您可以使用orderBy(对于多个动态orderBy子句)
$events = DB::table('news')->where('category', $input['type']);
foreach ($input as $key => $value) {
$events->orderBy($key); // also, you can use ASC/DESC as second argument
}
$result = $users->get();
或者你可以使用
$result = $users->paginate(10);
标签:php,variables,laravel,eloquent
来源: https://codeday.me/bug/20190629/1326137.html