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

hykeda8个月前ThinkPHP296

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

相关文章

在thinkphp6.1.1中composer安装 liliuwei/thinkphp-jump报错

报错内容:Problem 1     - Root composer.json requires liliu...

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

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

thinkphp 行为Hook 使用说明

关于tp的钩子功能,梳理下: 添加行为标签位: tp默认在tags.php文件中已经添加了: return [ // 应用初始化...

thinkphp项目接入阿里云OSS

1、首先安装 sdk:composer require aliyuncs/oss-sdk-php安装好后,在控制器中创建上传方法:protected function upload...

thinkphp6 中间件使用笔记

最近开发三频道打通程序时用到了中间件,现总结一下:第一步:首先用命令行生成中间件php think make:middleware Check这个指令会 app...

发表评论    

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