命名範圍 讓模型查詢條件「一次定義、多處復用」,通過 _scope 屬性與 scope() 方法實現查詢邏輯的標準化、模組化,是團隊協作與代碼治理的利器。
class NewsModel extends Model {
protected $_scope = [
'normal' => [
'where' => ['status' => 1],
],
'latest' => [
'order' => 'create_time DESC',
'limit' => 10,
],
];
}
| 屬性 | 說明 |
|---|---|
| where | 查詢條件 |
| field | 查詢字段 |
| order | 排序 |
| table | 表名 |
| limit | 結果限制 |
| page | 分頁 |
| having | HAVING 條件 |
| group | GROUP BY |
| lock | 鎖定 |
| distinct | 去重 |
| cache | 查詢緩存 |
$Model = D('News'); // 必須用 D 方法
$Model->scope('normal')->select(); // WHERE status=1
$Model->scope('latest')->select(); // ORDER BY create_time DESC LIMIT 10
$Model->scope('normal')->scope('latest')->select();
// 或簡寫
$Model->scope('normal,latest')->select();
// SQL: WHERE status=1 ORDER BY create_time DESC LIMIT 10
後調用範圍覆蓋同屬性定義。
$Model->scope('normal,new')->select(); // 僅 normal 生效
protected $_scope = [
'default' => [
'where' => ['status' => 1],
'limit' => 10,
],
];
$Model->scope()->select(); // 等效 scope('default')
$Model->scope('default')->select(); // 顯式調用
// 基於 normal 覆蓋 limit
$Model->scope('normal', ['limit' => 5])->select();
// SQL: WHERE status=1 LIMIT 5
// 基於多範圍調整
$Model->scope('normal,latest', ['limit' => 5])->select();
$Model->scope([
'field' => 'id,title',
'limit' => 5,
'where' => 'status=1',
'order' => 'create_time DESC'
])->select();
$Model->scope('normal')->limit(8)->order('id desc')->select();
// 後調用覆蓋:LIMIT 8, ORDER BY id DESC
$Model->limit(8)->scope('normal')->order('id desc')->select();
// 先 LIMIT 8 再 scope 覆蓋 LIMIT 10 → 最終 LIMIT 10
專案經理規劃命名範圍,開發人員直接調用,避免 CURD 操作中的條件錯誤、邏輯不一致,實現查詢邏輯的標準化治理。
published、hot、recentdefault 範圍實現基礎過濾(如軟刪除 status=1)