关于thinkphp6 where以数组形式查询,其中有or,and的处理

hykeda3年前ThinkPHP3399

最近在写tp6的查询语句时,如果查询条件以数组形式传入,比如:

$where[] = ['id','=',$id];
$where[] = ['openid','=',$openid];
$where[] = ['mobile','=',$mobile];
$model->where($where)->find();

这样的写法,sql语句时用and相连的。但是现在如果需要有用到or的话,可以使用whereOr

但是如果是另个字段,同时等于一个值,并且是or,那么要这样写:

$where[] = ['openid|mobile','=',‘kkkkkkkkkkk’];

这样生成的sql是:id=1 and (openid=‘kkkkkkkkk’or mobile=‘kkkkkkkkk)。

但是现在我想要生成的sql是这样的:id=1 and (openid = 'asdfasdfasdfasdfasdf' or mobile='13333333333')。

以前用tp可以写成:

$where[] = [['openid','=',‘asdfasdfasdfasdfasdf’],['mobile','=',‘13333333333’],or];

但是现在这种写法tp6已经不支持了,现在必须用闭包的写法来实现:

新创建一个$map的变量:

$where[] = ['id','=',$id];
$map[] = ['openid','=',$openid];
$map[] = ['mobile','=',$mobile];
$model->where($where)->where(function($query) use ($map){
    $query->whereOr($map);
})->find();

这样写就能实现上面所说的sql语句

相关文章

phpqrcode防止输出乱码 thinkphp

/** * 封装生成二维码函数 * */ function getQrcode($url){ /*生成二维码*/ vendor("phpqrcod...

composer升级thinkphp版本

之前用的thinkphp版本为tp5.0.12,最近tp已经更新到5.0.19以及5.1版本的5.1.12。 我一开始在目录下面直接使用了composer update...

thinkphp6 使用中的注意点

thinkphp6 使用中的注意点

1、TP6中采用多应用模式需要安装  composer require topthink/think-multi-app如果需要使用view,还必须安装模板引擎...

关于thinkphp5.1钩子和行为的个人理解和使用

关于thinkphp5.1钩子和行为的个人理解和使用

thinkphp5中的钩子和行为属于AOP编程思想,类似于AOP编程中的“切面”的概念,简单理解就是一个切入点,可以大大增加程序的耦合性。如何使用钩子和行为来开发:首先在项目中创建一个行为文件夹:1、...

thinkphp6.1中分页类调用

$list = YourModel->paginate([     'list_rows' =>&n...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。