Revision #5 has been created by yiqing95 on Dec 3, 2011, 3:56:36 AM with the memo:
add alias functionality then you can use in relation scenario without column name conflict. and you can config an different name from 'CreateAt'
« previous (#4) next (#6) »
Changes
Title
unchanged
How to add a named scope to ActiveRecords with a behavior
Category
unchanged
Tutorials
Yii version
unchanged
Tags
unchanged
Content
changed
[...]
}
```
That's it. Our named scope is ready to use with `Post`. Feel free to improve the above code or come up with your own ideas for named scopes that are good candidates for a behavior.
some improvement:
```php
class BetweenBehavior extends CActiveRecordBehavior
{
/**
* @var string
* here you can config it if you have a different name from 'CreateAt'
*/
public $attrCreateAt = 'CreatedAt ';
/**
* @param $start
* @param $end
* @param null $alias
* you can specify an alias here which can be the current ActiveRecord( normally is 't') or relation Ar 's alias(the relation name)
* @return CActiveRecord
*/
public function between($start,$end,$alias=null)
{
$alias = empty($alias)? $this->getOwner()->getTableAlias() : $alias;
if(empty($alias)){
$condition = $this->attrCreateAt.' BETWEEN :start AND :end';
}else{
$condition = $alias.'.'.$this->attrCreateAt.' BETWEEN :start AND :end';
}
$this->Owner->getDbCriteria()->mergeWith(array(
'condition'=> $condition,
'params'=>array(':start'=>$start, ':end'=>$end)
));
return $this->Owner;
}
}
usage:
class Post extends CActiveRecord {
// ...
public function behaviors()
{
return array(
'BetweenBehavior' => array(
'class'=>'BetweenBehavior',
'attrCreateAt' = 'createTime',
)
);
}
// ...
}
```
***
# 如何用行为(behavior)给数据记录(ActiveRecords)添加命名范围
从yii 1.0.5版本开始你可以使用ActiveRecords的命名范围(Name scopes),对于我们简化数据库的查询请求有很大的帮助,例如,你有很多带有"CreateAt"的数据表,它是一个整数的UNIX的时间戮,现在我们想添加一个命名范围 between($start,$end),我们数据记录都可以方便的使用如下查询方法。[...]