ThinkPHP5 WHERE AND OR 實現多條件查詢
阿新 • • 發佈:2020-11-28
問題:ThinkPHP查詢條件中包含 AND 和 OR 的條件該如何編寫程式碼。
1、查詢條件
1 // 基本查詢條件 2 $where = [ 3 ['is_shelves', '=', 1], 4 ['is_delete_time', '=', 0], 5 ]; 6 7 // 關鍵詞查詢 8 $where_keywords = [ 9 ['title|address|vice_title|describe', 'LIKE', '%' . $params['keyword'] . '%'], 10 ]; 1112 // 範圍查詢條件 13 $where_range = [ 14 ['lng', '>=', $range['minlng']], 15 ['lng', '<=', $range['maxlng']], 16 ['lat', '>=', $range['minlat']], 17 ['lat', '<=', $range['maxlat']], 18 ];
2、使用ThinkPHP5進行查詢
1 $data = Db::name('ParkApply')->field($field) 2 ->where(function($query) use ($where){ 3 $query->where($where); 4 }) 5 ->where(function($query) use ($where_range, $where_keywords){ 6 $query->where($where_keywords); 7 $query->whereOr(function ($query) use($where_range) { 8 $query->where($where_range); 9 }); 10 }) 11 ->order($order_by)->limit($m, $n)->select();
3、生成的SQL
1 SELECT * FROM `s_park_apply` WHERE ( `is_shelves` = 1 AND `is_delete_time` = 0 ) AND ( ( `title` LIKE '%銀輝路%' OR `address` LIKE '%銀輝路%' OR `vice_title` LIKE '%銀輝路%' OR `describe` LIKE '%銀輝路%' ) OR ( `lng` >= 105.4528834087 AND `lng` <= 105.4631557269 AND `lat` >= 28.89358913307 AND `lat` <= 28.90258234913 ) ) ORDER BY `id` DESC LIMIT 0,20
參考部落格連結:
ThinkPHP 5.0 組合多條件whereOr查詢
https://blog.csdn.net/weixin_43837229/article/details/101535227
ThinkPHP5框架where實現or查詢的兩種方法
https://blog.csdn.net/weixin_42330073/article/details/86496940