ThinkPHP 模型 (M()/D()) 回傳物件支援方法鏈,終端方法 (select/find/save/delete) 執行實際 SQL。中間方法可任意順序、多次呼叫。
| 方法 | 參數型態 | 說明 | 範例 |
|---|---|---|---|
where | 字串/陣列/物件 | 查詢條件 | where('id>5')、where(['status'=>1,'type'=>2]) |
order | 字串/陣列 | 排序 | order('id DESC')、order(['id'=>'DESC','name'=>'ASC']) |
limit | 字串/整數/陣列 | 限制筆數 | limit(10)、limit(5,10)、limit('5,10') |
field | 字串/陣列/布林 | 指定/排除欄位 | field('id,name')、field(['nickname'=>'name'])、field('id',true) 排除 id |
table | 字串/陣列 | 指定資料表 (含前綴) | table('__PREFIX__user u') |
group | 字串 | GROUP BY | group('category_id') |
having | 字串 | HAVING 條件 | having('COUNT(*)>5') |
join | 字串/陣列 | JOIN 關聯表 | join('LEFT JOIN profile p ON u.id=p.uid') |
union | 字串/陣列/物件 | UNION 查詢 | union('SELECT * FROM user_archive') |
distinct | 布林 | DISTINCT | distinct(true) |
lock | 布林 | FOR UPDATE / LOCK IN SHARE MODE | lock(true) |
cache | 混合 | 查詢快取 | cache(true, 300, 'user_list') |
relation | 字串 | 關聯模型查詢 | relation('profile') |
validate | 陣列 | 自動驗證規則 | validate(['name'=>'require']) |
auto | 陣列 | 自動完成規則 | auto(['create_time'=>['time','function']]) |
filter | 字串 | 資料過濾函數 | filter('htmlspecialchars') |
scope | 字串/陣列 | 命名範圍 | scope('latest') |
<?php
// 分頁查詢:最新 10 筆已發布文章,含作者暱稱
$list = M('Article')
->where(['status' => 1])
->order('publish_time DESC')
->limit(10)
->field('id,title,publish_time,author_id')
->join('LEFT JOIN __USER__ u ON Article.author_id=u.id')
->field('u.nickname', true) // 追加欄位
->select();
// 統計:各分類文章數 (含 0)
$stats = M('Category')
->field('Category.id, Category.name, COUNT(Article.id) AS cnt')
->join('LEFT JOIN __ARTICLE__ Article ON Category.id=Article.cate_id')
->group('Category.id')
->select();
// 事務中鎖定行更新
M('Account')->startTrans();
$acc = M('Account')->where(['id'=>1])->lock(true)->find();
$acc['balance'] -= 100;
M('Account')->save($acc);
M('Account')->commit();
page(2, 15) 內部轉為 limit(15, 15),語意更清晰。alias('u') 給主表別名,配合 join 簡化欄位引用。filter('strip_tags') 寫入前自動過濾,配合 auto 實現 XSS 防護。echo M()->_sql(); (需在終端方法前呼叫)。where,否則全表操作。field('id', true) 為「排除 id」,易誤解為「只取 id」。where 會 AND 組合,非覆蓋。cache() 需配置快取驅動 (Redis/Memcache/File),否則無效。