Difference between #2 and #6 of
How to add a named scope to ActiveRecords with a behavior

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(false) : $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',
 
              )
 
        );
 
    }
 
 
    // ...
 
}
 
 
// with relation query  ,the CreateAt is from Comment class. haven't test this funcitonality
 
$posts=Post::model()->between($start,$end,'comments')->with('comments')->findAll();
 
```
 
 
 
***
 
 
如何用行为(behavior)给数据记录(ActiveRecords)添加命名范围

从yii 1.0.5版本开始你可以使用ActiveRecords的命名范围(Name scopes),对于我们简化数据库的查询请求有很大的帮助,例如,你有很多带有"CreateAt"的数据表,它是一个整数的UNIX的时间戮,现在我们想添加一个命名范围 between($start,$end),我们数据记录都可以方便的使用如下查询方法。

~
```php
[...]
2 0
10 followers
Viewed: 35 889 times
Version: 1.1
Category: Tutorials
Tags:
Written by: Mike
Last updated by: yiqing95
Created on: Apr 30, 2009
Last updated: 12 years ago
Update Article

Revisions

View all history