6.16 命名范围
匿名 · 更新于 2013/12/25
模型命名范围功能,给模型操作提供了一系列的(连贯操作)封装,让你更方便的查询和操作数据。
定义属性
要使用命名范围功能,主要涉及到模型类的_scope属性定义和scope连贯操作方法的使用。我们首先定义_scope属性:
class NewsModel extends Model {protected $_scope = array(// 命名范围normal'normal'=>array('where'=>array('status'=>1),),// 命名范围latest'latest'=>array('order'=>'create_time DESC','limit'=>10,),);}
'命名范围标识名'=>array('属性1'=>'值1','属性2'=>'值2'...)
命名范围标识名:可以是任意的字符串,用于标识当前定义的命名范围。
命名范围支持的属性包括:
| where | 查询条件 |
| field | 查询字段 |
| order | 结果排序 |
| table | 查询表名 |
| limit | 结果限制 |
| page | 结果分页 |
| having | having查询 |
| group | group查询 |
| lock | 查询锁定 |
| distinct | 唯一查询 |
| cache | 查询缓存 |
方法调用
属性定义完成后,接下来就是使用scope方法进行命名范围的调用了,每调用一个命名范围,就相当于执行了命名范围中定义的相关操作选项。调用某个命名范围
最简单的调用方式就直接调用某个命名范围,例如:$Model->scope('normal')->select();$Model->scope('latest')->select();
SELECT * FROM think_news WHERE status=1SELECT * FROM think_news ORDER BY create_time DESC LIMIT 10
调用多个命名范围
也可以支持同时调用多个命名范围定义,例如:$Model->scope('normal')->scope('latest')->select();
$Model->scope('normal,latest')->select();
SELECT * FROM think_news WHERE status=1 ORDER BY create_time DESC LIMIT 10
如果调用的命名范围标识不存在,则会忽略该命名范围,例如:
$Model->scope('normal,new')->select();
SELECT * FROM think_news WHERE status=1
默认命名范围
系统支持默认命名范围功能,如果你定义了一个default命名范围,例如:protected $_scope = array(// 默认的命名范围'default'=>array('where'=>array('status'=>1),'limit'=>10,),);
$Model->scope()->select();
$Model->scope('default')->select();
命名范围调整
如果你需要在normal命名范围的基础上增加额外的调整,可以使用:$Model->scope('normal',array('limit'=>5))->select();
SELECT * FROM think_news WHERE status=1 LIMIT 5
$Model->scope('normal,latest',array('limit'=>5))->select();
SELECT * FROM think_news WHERE status=1 ORDER BY create_time DESC LIMIT 5
自定义命名范围
又或者,干脆不用任何现有的命名范围,我直接传入一个命名范围:$Model->scope(array('field'=>'id,title','limit'=>5,'where'=>'status=1','order'=>'create_time DESC'))->select();
SELECT id,title FROM think_news WHERE status=1 ORDER BY create_time DESC LIMIT 5
与连贯操作混合使用
命名范围一样可以和之前的连贯操作混合使用,例如定义了命名范围_scope属性:protected $_scope = array('normal'=>array('where'=>array('status'=>1),'field'=>'id,title','limit'=>10,),);
$Model->scope('normal')->limit(8)->order('id desc')->select();
SELECT id,title FROM think_news WHERE status=1 ORDER BY id desc LIMIT 8
如果是这样调用:
$Model->limit(8)->scope('normal')->order('id desc')->select();
SELECT id,title FROM think_news WHERE status=1 ORDER BY id desc LIMIT 10
