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

hykeda2年前ThinkPHP2017

最近在写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语句

相关文章

phpExcel 官方停止更新,不支持php7.4以上版本,改用 phpspreadsheet

composer require phpoffice/phpspreadsheet安装后:按需要引入文件use PhpOffice\PhpSpreadsheet\Spre...

记录thinkphp3.13移植到php7过程

随着php7的兴起,越来越多的公司用php7了,下面记录一次thinkphp3.1.3项目移植到php7解决兼容性的过程。 先在thinkphp...

最新阿里云OSS文件上传部署

1、前往阿里云github下载SDK包:https://github.com/aliyun/aliyun-oss-php-sdk/releases。 这里介绍源码部署:Source code下载下来...

关于thinkphp5.1中间件的使用

关于thinkphp5.1中间件的使用

在tp5.1开始,有了中间件的概念。 首先中间件主要用于拦截或过滤应用的HTTP请求,并进行必要的业务处理。 生成中间件: php thin...

thinkphp5.1 使用第三方类库放置在extend文件夹

thinkphp5.1 使用第三方类库放置在extend文件夹

thinkphp5.1 开发扩展类库时,命名空间必须要命名成文件夹的名字,不然无法访问到:...

Thinkphp5 记录点,注意点

json对象转成数组 先用$flag->getContent() $flag = json_decode($flag->getContent(),true); 控制器: 1、当控制器...

发表评论    

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