thinkphp查询条件被叠加

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值