有时候,用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文档手册已经说了,没有仔细看的就会踩到这个坑。


在ThinkPHP中,如果一个类的方法被控制器多次调用,可能会遇到查询条件叠加的问题,导致后续查询无法得到预期结果。文章通过示例展示了这个问题,并提出了解决方案,即在每次查询前使用`removeOption(where)`重置条件,确保每个查询的条件独立,从而避免数据查询错误。这提醒开发者在使用框架时需要注意代码的执行逻辑和框架的特性。
613

被折叠的 条评论
为什么被折叠?



