企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
SELECT * FROM `tp_finance` WHERE `subject` = '生产费用' AND `project` = '主料' OR `subject` = '生产费用' OR `project` = '材料运费' ``` Db::name('finance') ->where([['subject','=','生产费用'],['project','=','主料']]) ->whereOr([['subject','=','生产费用'],['project','=','材料运费']]) ->select(); ``` **注意,相同的字段的多次查询条件可能会合并,如果希望某一个`where`方法里面的条件单独处理,可以使用下面的方式,避免被其它条件影响。** SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' AND `title` LIKE '%thinkphp' AND `id` > 0 ) AND `status` = '1' ~~~ $map = [ ['name', 'like', 'thinkphp%'], ['title', 'like', '%thinkphp'], ['id', '>', 0], ]; Db::table('think_user') ->where([ $map ]) ->where('status',1) ->select(); ~~~ **在多个字段之间用`|`分割表示`OR`查询,用`&`分割表示`AND`查询** SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' OR `title` LIKE 'thinkphp%' ) AND ( `create_time` > 0 AND `update_time` > 0 ) LIMIT 1 ~~~ Db::table('think_user') ->where('name|title','like','thinkphp%') ->where('create_time&update_time','>',0) ->find(); ~~~ SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' AND `title` LIKE '%thinkphp' ) OR ( `name` LIKE 'kancloud%' AND `title` LIKE '%kancloud' ) ~~~ $map1 = [ ['name', 'like', 'thinkphp%'], ['title', 'like', '%thinkphp'], ]; $map2 = [ ['name', 'like', 'kancloud%'], ['title', 'like', '%kancloud'], ]; Db::table('think_user') ->whereOr([ $map1, $map2 ]) ->select(); ~~~ ## **闭包查询WHERE(function)** **每个闭包条件两边也会自动加上括号** SELECT * FROM `think_user` WHERE ( `name` = 'thinkphp' OR `id` > 10 ) ~~~ $name = 'thinkphp'; $id = 10; Db::table('think_user')->where(function ($query) use($name, $id) { $query->where('name', $name) ->whereOr('id', '>', $id); })->select(); ~~~ SELECT * FROM `think_user` WHERE `name` LIKE 'thinkphp%' AND ( `id` < 10 ) ~~~ Db::table('think_user') ->where('name', 'like', 'thinkphp%') ->where(function ($query) { $query->where('id', '<', 10); }) ->select(); ~~~ ## **whereRaw:原生SQL语句进行查询** 对于一些实在复杂的查询,也可以直接使用原生SQL语句进行查询,例如: ~~~ Db::table('think_user') ->whereRaw('id > 0 AND name LIKE "thinkphp%"') ->select(); ~~~ 为了安全起见,我们可以对字符串查询条件使用参数绑定,例如: ~~~ Db::table('think_user') ->whereRaw('id > :id AND name LIKE :name ', ['id' => 0, 'name' => 'thinkphp%']) ->select(); ~~~