有时候,用thinkphp写了一个类,用控制器调用多次,发现条件都叠加起来了
//逻辑类
class Module_article extends Model
{
...
public fucntion article_info($condition=[]){
$info=Db::name("module_article")->where($condition)->find();
echo Db::name("module_article")->getLastSql().'<br>';
}
}
//控制器类调用
class Article extends \think\Controller
{
...
$info1 = $this->article_logic->article_info(['type','eq',1]);
$info2= $this->article_logic->article_info(['type','eq',2]);
$this->assign('info1',$info1);
$this->assign('info2',$info2);
}
以上SQL输出:
select * from article where type =1;
select * from article where type =1 && type=2;
第二个显然不是我们想要的,永远查不到数据。
我们可以通过removeOption('where'),将条件重置为空,逻辑类变成:
//逻辑类
class Module_article extends Model
{
...
public fucntion article_info($condition=[]){
$info=Db::name("module_article")->removeOption('where')->where($condition)->find();
echo Db::name("module_article")->getLastSql().'<br>';
}
}
以上SQL输出:
select * from article where type =1;
select * from article where type=2;
完美解决thinkphp条件叠加的问题,防止查不到数据。
其实TP文档手册已经说了,没有仔细看的就会踩到这个坑。