【发布时间】:2012-09-14 00:05:14
【问题描述】:
我想知道是否有一种方法可以检测 yii 中的 AR 搜索是否正在使用范围?
例如,一个模型可能包含 2 个作用域:
class MyModel extends CActiveRecord
{
...
function myScope1()
{
$this->getDbCriteria()->mergeWith(array(
'join'=>'etc...',
'condition'=>'foo = bar',
));
return $this;
}
function myScope2()
{
$this->getDbCriteria()->mergeWith(array(
'join'=>'etc...',
'condition'=>'foo2 = bar2',
));
return $this;
}
....
}
我这样称呼 AR:
$results = MyModel::model()->myScope1()->myScope2()->findAll();
这是一个非常动态的网站,有超过 2 个范围,有些使用,有些没有。如果正在使用另一个范围,则不应应用几个范围。为了避免数百个if else 声明,我可以这样做:
class MyModel extends CActiveRecord
{
...
function myScope1()
{
$this->getDbCriteria()->mergeWith(array(
'condition'=>'foo = bar',
));
return $this;
}
function myScope2()
{
if($this->appliedScopes('myScope1')==false)
{
// scope myScope1 isn't applied, so apply this scope:
$this->getDbCriteria()->mergeWith(array(
'condition'=>'foo2 = bar2',
));
}
return $this;
}
....
}
【问题讨论】:
标签: yii scopes named-scopes