TP5中update时避免验证字段重复的解决方法

比如当你修改一个前台轮播图的信息,其他信息要修改后,只有排序这个关键字段不需要修改,但是在验证里边写了unique验证规则(排序不能重复),那么此时就会显示排序不能重复的验证后的报错信息,但是此时真的不需要改当前的排序。此时删掉再添加会很不友好,如果在更新时的验证场景中去掉unique这个规则的话,那么当需要改排序的时候就会没有这个验证规则,就会容易造成修改的排序与现有的排序产生冲突。此时,只要加一个条件判断即可解决以上问题:

		     public function update()
			{		
				$id=input('id');
			 	$services=db('services')->find($id);//获取一条数据	
			 	$this->assign('services',$services);
			 	
				if(request()->isPost())//request判断是否表单已经提交过来,如果是POST表单提交过来的,就要处理数据,记得要加return
				{
					if(input('sort')==$services['Sort'])
					{
						$data=[
						'Id'=>input('id'),
						'Title'=>input('title'),
						'Summary'=>input('summary'),
						'Content'=>input('content'),
						];
						$validate = new Validateuser;
						if(!$validate->scene('update2')->check($data))
						{
							$this->error($validate->getError());die;
						}
						if(db('services')->update($data))//此处把Id写到了data数组里,所以此处省略了where
						{
							return redirect('services');
						}
						else
						{
							$this->error('修改前台服务信息失败');
						}
						 return ;//加一个return将不再显示下面的语句
					}else{
						$data=[
						'Id'=>input('id'),
						'Sort'=>input('sort'),
						'Title'=>input('title'),
						'Summary'=>input('summary'),
						'Content'=>input('content'),
						];
						$validate = new Validateuser;
						if(!$validate->scene('update')->check($data))
						{
							$this->error($validate->getError());die;
						}
						if(db('services')->update($data))//此处把Id写到了data数组里,所以此处省略了where
						{
							return redirect('services');
						}
						else
						{
							$this->error('修改前台服务信息失败');
						}
						 return ;//加一个return将不再显示下面的语句
						}
					}
					 	return $this->fetch('update');	 
			}

猜你喜欢

转载自blog.csdn.net/zhaojie911272507/article/details/81665729
今日推荐