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

ThinkPHP 3.1 命名範圍:模型查詢條件的封裝與復用藝術

     編輯:PHP 相關知識

命名範圍 讓模型查詢條件「一次定義、多處復用」,通過 _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分頁
havingHAVING 條件
groupGROUP 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、recent
  • 避免過度細碎,合併高頻組合
  • 配合 default 範圍實現基礎過濾(如軟刪除 status=1)
  • 文檔化所有範圍定義,新人速查
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved