我正在使用Laravel 9,并使用数据库上的分页方法显示一些数据。我的表上方还有一个搜索字段,用它来过滤结果。在过滤时,我过滤数据并对其调用paginate方法。这就是问题所在。假设我在过滤前在第6页,过滤后结果汇总为两页,但是paginate方法将我重定向到第6页,而这又不会显示任何结果。
下面是我的代码示例:第一次页面:
$modelData = Model::orderBy('id', 'DESC')->paginate(20);
过滤后:
$search = $_GET['searchField'];
$modelData = Model::where("name", "LIKE", "%{$search}%")->paginate(2);
我希望它把我带到结果的第一页,但它把我带到我搜索列表的页面。
编辑:My Complete function:
public function index()
{
$sortData = $searchData = NULL;
//CHECKS FOR SORTING, SEARCH AND BOTH
if (isset($_GET['sort']) && !empty($_GET['sort']) && isset($_GET['searchField']) && !empty($_GET['searchField'])) {
$search = $_GET['searchField'];
$modelData = Model::where("name", "LIKE", "%{$search}%")->orderBy($_GET['sort'], $_GET['direction'])->paginate(10);
$sortData = $_GET;
$searchData = $search;
} elseif (isset($_GET['sort']) && !empty($_GET['sort'])) {
$modelData = Model::orderBy($_GET['sort'], $_GET['direction'])->paginate(10);
$sortData = $_GET;
} elseif (isset($_GET['searchField']) && !empty($_GET['searchField'])) {
$search = $_GET['searchField'];
$modelData = Model::where("name", "LIKE", "%{$search}%")->paginate(10);
$searchData = $search;
} else {
$modelData = Model::orderBy('id', 'DESC')->paginate(10);
}
return view('content.view.list', compact(
'modelData',
'sortData',
'searchData'
));
}
-
我认为你不应该使用$_GET
$request->query('sort') $request->query('direction')
-
既然使用了!empty(),就不需要使用isset()。
-
你不需要$search,因为
$search = $_GET['searchField']; ... $searchData = $search;
$searchData = $_GET['searchField'];
您也不需要$searchData。因为$sortData = $_GET。
你已经有了整个$_GET,为什么你想重新定义它的一个元素?$ sortData [' searchField ']我认为searchData的英文含义比sortData好。因为sortData意味着需要排序的数据。虽然searchData表示执行搜索任务所需的数据,但执行过滤工作。所以searchData应该是$_GET。
我建议:
public function index()
{
$searchData= $request->query(); // This is $_GET
// See what is your $_GET
//echo "<pre>".print_r($searchData, 1)."</pre>"; exit;
$model = Product::query(); //Initialize query builder
if(!empty($searchData['searchField']))){
$model->where('name', 'LIKE', '%'.$searchData['searchField'].'%');
}
if(!empty($searchData['sort']))){
$sort = $searchData['sort'];
}else{
$sort = 'id'; // default use id
}
if(!empty($searchData['direction'])){
$direction = $searchData['direction'];
}else{
$direction = 'DESC'; // default use desc
}
$model->orderBy($sort, $direction);
// This can see the SQL content, and it should before result like paginate() or get(). I think...
if(!empty($searchData['debug'])){
$debugData['sql'] = $query->toSql();
$debugData ['bidings'] = $query->getBindings();
echo "<pre>".print_r($debugData , 1)."</pre>"; exit;
}
if(!empty($searchData['limit'])){
$limit = $searchData['limit'];
}else{
$limit = 10;
}
$modelData = $model->paginate($limit)->appends($queries);
return view('content.view.list', compact(
'searchData',
'modelData',
));