场景:
数据表结构如下:
CREATE TABLE `cityarea` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`phone` varchar(30) NOT NULL,
`city_id` int(11) NOT NULL,
`area_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1DEFAULT CHARSET=utf8mb4
已知会员的cityid\areaid,areaid可能为空。cityarea表记录city_id和area_id是一对多。
目的:会员每次请求,需要得到不同列表数据
实现方案:
1、精准匹配,市区全匹配
2、精准匹配无数据,切换市匹配
3、市首次匹配无数据,终止请求。如果没有此判断,会造成死循环。
4、直到市匹配无数据,切换市区匹配,以此循环,需要用到递归
代码:
public function list(){
$cityid = $this->cityid;
$areaid = $this->areaid;
// 判断注册时的市信息
if(empty($cityid)){
return json_encode(['msg'=>MISSING_AREA_PARAMETERS,'code'=>ERROR_NOTICE_CODE]);
}
$wstr=json_encode(array('city_id'=>$cityid, 'area_id'=>$areaid));
$cuss = $this->getlist($cityid,$areaid,$wstr);// 递归函数
if(!empty($cuss)){
return json_encode(['data'=>$cuss,'code'=>SUCCESS_OK_CODE]);
}else{
return json_encode(['msg'=>MISSING_AREA_PARAMETERS,'code'=>ERROR_NOTICE_CODE]);
}
}
public function getlist($cityid,$areaid,$wstr){
$arr=$this->cusspage($wstr,0,0);
$page=$arr['page'];
$type=$arr['type'];//1 市区匹配 2市匹配
if($type==1){
$w['city_id']=$cityid;
$w['area_id']=$areaid;
}else{
$w['city_id']=$cityid;
}
$cuss = Db::name('cityarea')
->where($w)
->page($page)
->order('id desc')
->select();
if(count($cuss)==0){
if($type==1){
$arr=$this->cusspage($wstr,0,2);//转市匹配
}elseif($type==2){
if($page==1){
return [];// 否则会死循环
}else{
$this->cusspage($wstr,0,1);//转市区匹配
}
}
return $this->getlist($cityid,$areaid,$wstr);
}else{
return $cuss;
}
}
public function cusspage($where,$resetpage,$type){
$redis = new \Redis;
$redis->connect('127.0.0.1', '8888');
$redis->auth('88888');
$is = $redis->exists("cussphone:".$this->uid.md5($where));
if($is==1){
//存在
$redis->hIncrBy("cussphone:".$this->uid.md5($where),"page",1);
}else{
//不存在
$redis->set(md5($this->uid.$where),1);
$redis->lPush("cussphone:uid",$this->uid.md5($where));
$redis->hMset("cussphone:".$this->uid.md5($where),array('uid'=>$this->uid,'where'=>$where,'type'=>1,'page'=>1));
}
if($type==1){
$redis->hSet("cussphone:".$this->uid.md5($where),"type",1);
$redis->hSet("cussphone:".$this->uid.md5($where),"page",0);
}elseif ($type==2){
$redis->hSet("cussphone:".$this->uid.md5($where),"type",2);
$redis->hSet("cussphone:".$this->uid.md5($where),"page",0);
}
return array('page'=>$redis->hGet("cussphone:".$this->uid.md5($where),'page'),'type'=>$redis->hGet("cussphone:".$this->uid.md5($where),'type'));
}