字元串拼接查詢 案例一:拼接字元串(多條件查詢) $where = ''; //定義字元串,用於拼接滿足條件的數據欄位 $value = []; // 定義空數組,用於接收值 if(!empty($nickname)){ $where .= ' AND nickname = :nickname'; ...
- 字元串拼接查詢
案例一:拼接字元串(多條件查詢)
$where = ''; //定義字元串,用於拼接滿足條件的數據欄位 $value = []; // 定義空數組,用於接收值 if(!empty($nickname)){ $where .= ' AND nickname = :nickname'; //數據表欄位 $value['nickname'] = $nickname; //賦值 } if(!empty($phone)){ $where .= ' AND mobile = :mobile'; $value['mobile'] = $phone; } if(!empty($user_status)){ $where .= ' AND user_status = :user_status'; $value['user_status'] = $user_status; } if(!empty($reg_start_end)){ $start_end = explode('|',$reg_start_end); if(!empty($start_end[0])){ $where .= ' AND create_time > :start_time'; $value['start_time'] = strtotime($start_end[0]); } if(!empty($start_end[1])){ $where .= ' AND create_time <= :end_time'; $value['end_time'] = strtotime($start_end[1]); } } if(!empty($is_proxy)){ $where .= ' AND is_proxy = :is_proxy'; $value['is_proxy'] = $is_proxy; } if(!empty($sex)){ $where .= ' AND gender = :gender'; $value['gender'] = $sex; }$list = $obj->whereRaw('1=1'.$where.'', $value)->limit($limit_start, $limit_length)->order('create_time', 'asc')->select(); //查詢滿足條件的數據
Db::table('表名') ->whereRaw('id = :id AND name LIKE :name ', ['id' => 0, 'name' => 'thinkphp%']) ->select(); //形成的原生sql語句.
案例二:快捷查詢
快捷查詢方式是一種多欄位相同查詢條件的簡化寫法,可以進一步簡化查詢條件的寫法,在多個欄位之間用|
分割表示OR
查詢,用&
分割表示AND
查詢,可以實現下麵的查詢,例如:Db::table('think_user') ->where('name|title','like','%thinkphp%') ->where('create_time&update_time','>',0) ->find();
生成的查詢SQL如下:
SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' OR `title` LIKE 'thinkphp%' ) AND ( `create_time` > 0 AND `update_time` > 0 ) LIMIT 1SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' OR `title` LIKE 'thinkphp%' ) AND ( `create_time` > 0 AND `update_time` > 0 ) LIMIT 1;
案例三: 拼接字元串查詢
$where = '';
if ($status != 'all') {
$where .= ' AND status=' . $status; //拼接滿足條件的表欄位
}