1.写搜索功能,用搜索器,代码如下:在model层中:
//title搜索器
public function searchTitleAttr($query, $value){
$query->where('title','like','%'.$value.'%');
}
//create_time搜索器
public function searchCreateTimeAttr($query, $value){
$query->whereBetweenTime('create_time',$value[0],$value[1]);
}
//搜索器、分页
public function getLists($likeKeys, $data,$num = 10){
$order = ['listorder' => 'desc','id' => 'desc'];
if(!empty($likeKeys)){
//搜索
$res = $this->withSearch($likeKeys,$data);
}else{
$res = $this;
}
$list = $res->whereIn('status',[0,1])
->order($order)
->paginate($num);
//echo ($this->getLastSql());
return $list;
}
2.发现问题,就是分页的话,就带上不了,搜索的参数,于是进行处理:
在控制器中:多返回了一个搜索参数:showSearch,供前端展示,以及分页的时候,传到后端。
public function index(){
$data = [];
$showSearch = [
'title' => '',
'time' => ''
];
$title = input('param.title','','trim');
$time = input('param.time','','trim');
if(!empty($title)){
$data['title'] = $title;
$showSearch['title'] = $title;
}
if(!empty($time)){
$data['create_time'] = explode(" - ",$time);
$showSearch['time'] = $time;
}
$goods = (new GoodsB())->getLists($data,5);
//dump($this->request->query());
return view('',[
'goods' => $goods,
'showSearch' => $showSearch
]);
}
前端:
laypage.render({ //分页
elem: 'pages'
, count: {$goods.total}
, theme: '#FFB800'
, limit: {$goods.per_page}
, curr: {$goods.current_page}
, jump :function (obj,first) {
if(!first){
//这里分页的,就会加上,搜索字段
location.href="?page="+obj.curr+"&title={$showSearch.title}&time={$showSearch.time}"
}
}
});
3.业务层中,主要处理控制器的参数:
//获取分页列表的数据
public function getLists($data, $num = 5){
$likeKeys = [];
if(!empty($data)){
$likeKeys = array_keys($data);//取出键
}
try{
$list = $this->model->getLists($likeKeys, $data, $num);
$result = $list->toArray();
//$result['render'] = $list->render();//分页样式
}catch (\Exception $e){
$result = \app\common\lib\Arr::getPaginateDefaultData($num);
}
return $result;
}
至此,分页,带上搜索就完成了。
上面只是一种通常的解决方法。
下面一中处理方法,也是需要掌握的:在控制器中,也是返回俩个搜索参数。然后直接在模型中的paginate方法中,写搜索的的功能。