关于thinkphp6 where以数组形式查询,其中有or,and的处理
最近在写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语句