首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

ThinkPHP CURD where 方法完全指南:字串/陣列/表達式/快捷/區間/組合查詢

     編輯:PHP 綜合知識

字串條件(建議配合預處理)

$User->where('type=1 AND status=1')->select();

// 3.1+ 預處理防注入
$Model->where("id=%d AND username='%s'", [$id, $username])->select();
$Model->where("id=%d AND username='%s'", $id, $username)->select();

陣列條件(推薦)

基本查詢

$map = ['name' => 'thinkphp', 'status' => 1];
$User->where($map)->select();
// WHERE `name`='thinkphp' AND `status`=1

表達式查詢

表達式含義範例
EQ=['eq', 100]
NEQ<>['neq', 100]
GT>['gt', 100]
EGT>=['egt', 100]
LT<['lt', 100]
ELT<=['elt', 100]
LIKE模糊['like', 'thinkphp%']
BETWEEN區間['between', '1,8']
IN列表['in', '1,5,8']
EXP原生 SQL['exp', 'IN (1,3,8)']
$map['id'] = ['gt', 100];
$map['name'] = ['like', 'thinkphp%'];
$map['id'] = ['between', [1, 8]];
$map['id'] = ['not in', '1,5,8'];
$map['id'] = ['exp', 'IN (1,3,8)'];

快捷查詢

// 同值多欄位 (OR)
$map['name|title'] = 'thinkphp';  // name='x' OR title='x'

// 異值多欄位 (AND)
$map['status&title'] = [1, 'thinkphp', '_multi' => true];
// status=1 AND title='thinkphp'

區間查詢(同欄位多條件)

$map['id'] = [['gt', 1], ['lt', 10]];           // (id>1) AND (id<10)
$map['id'] = [['gt', 3], ['lt', 10], 'or'];     // (id>3) OR (id<10)
$map['name'] = [['like', '%a%'], ['like', '%b%'], ['like', '%c%'], 'ThinkPHP', 'or'];

組合查詢

// _string: 混入原生 SQL
$map['id'] = ['neq', 1];
$map['_string'] = 'status=1 AND score>10';

// _complex: 子查詢封裝
$where['name'] = ['like', '%thinkphp%'];
$where['title'] = ['like', '%thinkphp%'];
$where['_logic'] = 'or';
$map['_complex'] = $where;
$map['id'] = ['gt', 1];
// (id>1) AND ((name LIKE ...) OR (title LIKE ...))

多次調用(3.1.3+)

$Model->where($map1)->where($map2)->where('status=1')->select();
// 陣列條件自動合併,字串條件僅保留第一次
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved